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阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容