Swift - 實(shí)現(xiàn)通訊錄界面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.創(chuàng)建導(dǎo)航控制器的根視圖
        let rootVC = ContactListViewController()
        //2.創(chuàng)建導(dǎo)航視圖控制器,并為他制定根視圖控制器
        let navigation = UINavigationController(rootViewController: rootVC)
        //3.將導(dǎo)航視圖控制器設(shè)置為window的根視圖控制器
        self.window?.rootViewController = navigation
        return true
    }

ContactListViewController.swift代碼如下:

import UIKit

class ContactListViewController: UITableViewController {

    let systemCell = "cell"

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

    }
    //刷新數(shù)據(jù)
    override func viewWillAppear(_ animated: Bool) {
        //重新讓tableView刷新數(shù)據(jù)
        self.tableView.reloadData()
    }
    //設(shè)置導(dǎo)航條
    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:- 添加聯(lián)系人
    func addContactAction(sender:UIBarButtonItem){

        //模態(tài)出添加聯(lián)系人的視圖
        let addContactVC = AddContactViewController()
        //添加導(dǎo)航條
        let rootNC = UINavigationController(rootViewController: addContactVC)
        //關(guān)聯(lián)AddContactViewController視圖
        self.present(rootNC, animated: true, completion: nil)



    }

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

    // MARK: - 表視圖數(shù)據(jù)源

    override func numberOfSections(in tableView: UITableView) -> Int {
        //返回有幾組數(shù)據(jù)
        //單例調(diào)用返回有多少個(gè)分區(qū)的方法
        return ContactManger.shared.numberOfSection()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //返回每組有幾條數(shù)據(jù)
        //單例調(diào)用返回每個(gè)分區(qū)有多少個(gè)cell的方法
        return ContactManger.shared.numberOfRowInSection(section: section)
    }
    //設(shè)置每個(gè)細(xì)胞
    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)
        //單例調(diào)用返回聯(lián)系人的方法
        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? {
        //單例調(diào)用返回區(qū)頭標(biāo)題的方法
        return ContactManger.shared.sectionHeaderTitle(section: section)
    }
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        //單例調(diào)用返回索引欄方法
        return ContactManger.shared.sectionTitle()
    }
    //點(diǎn)擊cell觸發(fā)的方法
    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)
    }
    //設(shè)置屬性
    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 = "請(qǐng)輸入姓名"
        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 = "請(qǐng)輸入電話"
        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
        //添加聯(lián)系人
        //單例調(diào)用聯(lián)系人的方法
        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
//聯(lián)系人管理
class ContactManger: NSObject {
    //單例屬性
    static let shared = ContactManger()
    //數(shù)據(jù)源
    var dataSource:[String:[Contact]] = Dictionary()
    //有序key值屬性
    var keys:[String] = Array()

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

        let firstLetter = name?.uppercasePinYinFirstLetter()

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

![Uploading 004_035925.png . . .]

003.png

Header.h代碼如下:

#ifndef Header_h
#define Header_h

#import "pinyin.h"

#endif /* Header_h */
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容