Swift - 實現通訊錄界面00

文件圖例.png

AppDelegate.swift代碼如下:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

//        let firstLetter = "范宇".uppercasePinYinFirstLetter()

        self.window = UIWindow(frame:UIScreen.main.bounds)
        self.window?.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        self.window?.makeKeyAndVisible()
        //1.創建導航控制器的根視圖
        let rootVC = ContactListViewController()
        //2.創建導航視圖控制器,并為他制定根視圖控制器
        let navigation = UINavigationController(rootViewController: rootVC)
        //3.將導航視圖控制器設置為window的根視圖控制器
        self.window?.rootViewController = navigation
        return true
    }

ContactListViewController.swift代碼如下:

import UIKit

class ContactListViewController: UITableViewController {

    let systemCell = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()
        //注冊導航欄
        self.setNavigationItem()
        //注冊cell
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: systemCell)

    }
    //刷新數據
    override func viewWillAppear(_ animated: Bool) {
        //重新讓tableView刷新數據
        self.tableView.reloadData()
    }
    //設置導航條
    func setNavigationItem(){
        self.navigationItem.rightBarButtonItem = self.editButtonItem
        self.title = "Contacts"
        let dic = [NSFontAttributeName:UIFont.systemFont(ofSize: 20.0),NSForegroundColorAttributeName:UIColor.cyan]
        self.navigationController?.navigationBar.titleTextAttributes = dic
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addContactAction))

    }
    //MARK:- 添加聯系人
    func addContactAction(sender:UIBarButtonItem){

        //模態出添加聯系人的視圖
        let addContactVC = AddContactViewController()
        //添加導航條
        let rootNC = UINavigationController(rootViewController: addContactVC)
        //關聯AddContactViewController視圖
        self.present(rootNC, animated: true, completion: nil)



    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - 表視圖數據源

    override func numberOfSections(in tableView: UITableView) -> Int {
        //返回有幾組數據
        //單例調用返回有多少個分區的方法
        return ContactManger.shared.numberOfSection()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //返回每組有幾條數據
        //單例調用返回每個分區有多少個cell的方法
        return ContactManger.shared.numberOfRowInSection(section: section)
    }
    //設置每個細胞
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: systemCell, for: indexPath)
        cell.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)
        //單例調用返回聯系人的方法
        let aContact = ContactManger.shared.contactShowByIndexPath(indexPath: indexPath)
        cell.textLabel?.text = aContact.name
        cell.detailTextLabel?.text = aContact.phone
        

        return cell
    }
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        //單例調用返回區頭標題的方法
        return ContactManger.shared.sectionHeaderTitle(section: section)
    }
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        //單例調用返回索引欄方法
        return ContactManger.shared.sectionTitle()
    }
    //點擊cell觸發的方法
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //顯示DetailViewController視圖
        let detailVC = DetailViewController()
        self.navigationController?.pushViewController(detailVC, animated: true)

    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

DetailViewController.swift代碼如下:

import UIKit

class DetailViewController: UIViewController {

    var photoView:UIImageView!
    var nameLable:UILabel!
    var photoLable:UILabel!
    var addressLble:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupView()

        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    }
    //設置屬性
    func setupView(){
        //圖片
        photoView = UIImageView(frame: CGRect(x: 132, y: 100, width: 150, height: 150))
        photoView.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        self.view.addSubview(photoView)
        //姓名
        nameLable = UILabel(frame: CGRect(x: 107, y: 260, width: 200, height: 40))
        nameLable.backgroundColor = #colorLiteral(red: 0.8549019694, green: 0.250980407, blue: 0.4784313738, alpha: 1)
        self.view.addSubview(nameLable)
        //電話
        photoLable = UILabel(frame: CGRect(x: 107, y: 310, width: 200, height: 40))
        photoLable.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)
        self.view.addSubview(photoLable)
        //住址
        addressLble = UILabel(frame: CGRect(x: 107, y: 360, width: 200, height: 120))
        addressLble.numberOfLines = 0
        addressLble.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
        self.view.addSubview(addressLble)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

AddContactViewController.swift代碼如下:

import UIKit

class AddContactViewController: UIViewController {

    var photoView:UIImageView!
    var nameField:UITextField!
    var phoneField:UITextField!
    var addressTextView:UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNavigationItem()
        self.setupViews()
        self.view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
    }
    func setupViews(){
        //圖片
        photoView = UIImageView(frame: CGRect(x: 132, y: 80, width: 150, height: 150))
        photoView.backgroundColor = #colorLiteral(red: 0.8549019694, green: 0.250980407, blue: 0.4784313738, alpha: 1)
        self.view.addSubview(photoView)
        //姓名
        nameField = UITextField(frame: CGRect(x: 107, y: 240, width: 200, height: 40))
        nameField.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
        nameField.placeholder = "請輸入姓名"
        nameField.borderStyle  = .roundedRect
        self.view.addSubview(nameField)
        //電話
        phoneField = UITextField(frame: CGRect(x: 107, y: 290, width: 200, height: 40))
        phoneField.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
        phoneField.placeholder = "請輸入電話"
        phoneField.borderStyle = .roundedRect
        self.view.addSubview(phoneField)
        //住址
        addressTextView = UITextView(frame: CGRect(x: 107, y: 340, width: 200, height: 120))
        addressTextView.text = "地址:"
        addressTextView.layer.borderWidth = 1.0
        addressTextView.layer.borderColor = UIColor.gray.cgColor
        self.view.addSubview(addressTextView)
    }
    //添加按鈕的方法
    func setNavigationItem(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(cancelAction))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(saveAction))
    }
    //MARK:- “取消”的按鈕
    func cancelAction(sender:UIBarButtonItem){
        self.dismiss(animated: true, completion: nil)
    }
    //MARK:- “保存”的按鈕
    func saveAction(sender:UIBarButtonItem){
        //判斷姓名或電話是否為空
        if nameField.text?.characters.count == 0 || phoneField.text?.characters.count == 0 {
            return print("姓名或電話為空")
        }
        let aContact = Contact()
        aContact.name = nameField.text
        aContact.phone = phoneField.text
        aContact.adress = addressTextView.text
        aContact.photo = photoView.image
        //添加聯系人
        //單例調用聯系人的方法
        ContactManger.shared.addContact(aContact: aContact)

        self.dismiss(animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Contact.swift代碼如下:

import UIKit

class Contact: NSObject {

    var name:String!
    var phone:String!
    var adress:String?
    var photo:UIImage?
    override init() {

    }
    init(name:String,phone:String,adress:String?,photo:UIImage?) {
        self.name = name
        self.phone = phone
        self.adress = adress
        self.photo = photo
    }
}

ContactManger.swift代碼如下:

import UIKit
//聯系人管理
class ContactManger: NSObject {
    //單例屬性
    static let shared = ContactManger()
    //數據源
    var dataSource:[String:[Contact]] = Dictionary()
    //有序key值屬性
    var keys:[String] = Array()

    //添加聯系人的方法
    func addContact(aContact:Contact){
        //兩種情況: 聯系人分組存在,直接根據分組名取出數組,添加即可
        //分組不存在,根據聯系人的姓名首字母,在dataSource中創建一個健值對
        let name = aContact.name

        let firstLetter = name?.uppercasePinYinFirstLetter()

        var group = dataSource[firstLetter!]
        if group == nil {//分組不存在
            //初始化數組
            group = Array<Contact>()
            group?.append(aContact)
            //分組不存在才添加key值
            keys.append(firstLetter!)
            //重新排序
            keys.sort()
        }else{//分組存在
            group?.append(aContact)
        }
        //對字典重新賦值
        dataSource[firstLetter!] = group
    }
    //返回tableView有多少個分區
    func numberOfSection() -> Int {
        return dataSource.count
    }
    //返回tableView每個分區有多少個cell
    func numberOfRowInSection(section:Int) -> Int {
        let key = keys[section]
        let group = dataSource[key]
        return (group?.count)!
    }
    //返回cell分區上要展示聯系人對象的方法
    func contactShowByIndexPath(indexPath:IndexPath) -> Contact{
        let key = keys[indexPath.section]
        let group = dataSource[key]
        return group![indexPath.row]
    }
    //返回分區標題方法
    func sectionHeaderTitle(section:Int) -> String{
        return keys[section]
    }
    //返回索引列表的方法
    func sectionTitle() -> [String]{
        return keys
    }
}
  • Swift調用OC文件流程圖:

![Uploading 004_035925.png . . .]

003.png

Header.h代碼如下:

#ifndef Header_h
#define Header_h

#import "pinyin.h"

#endif /* Header_h */
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,156評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,401評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,069評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,873評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,635評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,128評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,203評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,365評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,881評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,733評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,935評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,475評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,172評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,582評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,821評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,595評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,908評論 2 372

推薦閱讀更多精彩內容