swift實(shí)現(xiàn)通訊錄的增、刪功能

初學(xué) swift,今天使用swift實(shí)現(xiàn)了一個(gè)簡(jiǎn)單通訊錄的增刪功能,功能簡(jiǎn)單,邏輯清晰,大家共勉。

首先,在 AppDelegate.swift 中創(chuàng)建導(dǎo)航控制器,把 ViewController 設(shè)置為根視圖控制器

//
//  AppDelegate.swift
//  Swift03-1
//
//  Created by 奇二世界 on 16/6/14.
//  Copyright ? 2016年 YMN. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 創(chuàng)建導(dǎo)航控制器,并設(shè)置根視圖控制器
        window?.rootViewController = UINavigationController(rootViewController: ViewController())
        
        // Override point for customization after application launch.
        return true
    }

接下來(lái),創(chuàng)建好我們需要的類,方便后續(xù)的工作,具體類的功能已標(biāo)注,如下圖:


創(chuàng)建不同功能的類

第一步:在 ContactManager.swift 中實(shí)現(xiàn)模型的 增、刪 功能

//
//  ContactManager.swift
//  Swift03-1
//
//  Created by 奇二世界 on 16/6/14.
//  Copyright ? 2016年 YMN. All rights reserved.
//

import UIKit

class ContactManager: NSObject {

    // 將聯(lián)系人管理類聲明為單例類,管理所有聯(lián)系人的操作:增、刪
    static let shareIntance:ContactManager = {
    
        let contactManager = ContactManager()
        return contactManager
    }()
    
    // 所有聯(lián)系人的數(shù)組
    var contactArray:[Contact] = [Contact]()
    // 增加:
    func addContact(contact:Contact){
        // swift 中添加到數(shù)組中用 .append()
        contactArray.append(contact)
    }
    // 刪除:
    func removeContactByIndexPath(indexPath:NSIndexPath)
    {
        contactArray.removeAtIndex(indexPath.row)
    }
}

第二步:在模型Contact.swift中,創(chuàng)建屬性,重載初始化方法:

//
//  Contact.swift
//  Swift03-1
//
//  Created by 奇二世界 on 16/6/14.
//  Copyright ? 2016年 YMN. All rights reserved.
//

import UIKit

class Contact: NSObject {
    // 創(chuàng)建屬性
    var name:String?
    var gender:String?
    var age:String?
    var phone:String?
    
    // 重載初始化方法
    init(name:String, gender:String, age:String, phone:String) {
        super.init()
        self.name = name
        self.gender = gender
        self.age = age
        self.phone = phone
    }
}

第三步:在自定義 ContactCell.swift 中,關(guān)聯(lián)xib文件中的屬性:

//
//  ContactCell.swift
//  Swift03-1
//
//  Created by 奇二世界 on 16/6/14.
//  Copyright ? 2016年 YMN. All rights reserved.
//

import UIKit

class ContactCell: UITableViewCell {

    // 將xib中的label拖成屬性
    @IBOutlet var nameL: UILabel!
    
    @IBOutlet var ageL: UILabel!
    
    @IBOutlet var genderL: UILabel!
    
    @IBOutlet var phoneL: UILabel!
    
    // 根據(jù)contact給cell里面的標(biāo)簽賦值
    func cellWithContact(contact:Contact){
 
        nameL.text = contact.name
        ageL.text = contact.age
        genderL.text = contact.gender
        phoneL.text = contact.phone

    }
}

第四步:在 ViewController.swift 中鋪放界面,創(chuàng)建 tableView,注冊(cè)ContactCell,并實(shí)現(xiàn)代理中的方法

//
//  ViewController.swift
//  Swift03-1
//
//  Created by 奇二世界 on 16/6/14.
//  Copyright ? 2016年 YMN. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

        // 懶加載tableView
        lazy var tableView:UITableView = {
        let tableV = UITableView(frame: UIScreen.mainScreen().bounds,style: UITableViewStyle.Plain)
        tableV.delegate = self
        tableV.dataSource = self
        return tableV
    }()

// viewDidLoad
 override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加十個(gè)聯(lián)系人
        for i in 0..<10
        {
            let contact = Contact(name: "聯(lián)系人\(i)", gender: "男", age: "2\(i)", phone: "111-123\(i)")
            ContactManager.shareIntance.addContact(contact)
        }
        // 添加 tableView 視圖
        view.addSubview(tableView)

    navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addAction:")
    }
}

在延展中遵守協(xié)議,并實(shí)現(xiàn)協(xié)議中的方法:
延展的寫法 // extension 本類名:協(xié)議名{ }
注意:延展是寫在class類外面的(大括號(hào)之外)

extension ViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return   ContactManager.shareIntance.contactArray.count
    }
    
    // 返回cell
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ContactCell // cell 此時(shí)是 UITableViewCell 類型,強(qiáng)制轉(zhuǎn)換成 ContactCell
        // 將 cell 和Contact 關(guān)聯(lián) 
        let contect = ContactManager.shareIntance.contactArray[indexPath.row]
        cell.cellWithContact(contect)
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 110
    }
}

運(yùn)行之后的界面效果:


通訊錄主界面

主界面搭建好,接下來(lái)是點(diǎn)擊 cell ,跳轉(zhuǎn)到聯(lián)系人詳情界面,先將界面鋪放好,這次用純代碼實(shí)現(xiàn),大家可以根據(jù)自己的掌握的熟練程度來(lái)選擇實(shí)現(xiàn)的方式。
在 DetailViewController.swift 文件中:

//
//  DetailViewController.swift
//  Swift03-1
//
//  Created by 奇二世界 on 16/6/14.
//  Copyright ? 2016年 YMN. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController {
    // 聲明模型的屬性,方便后面的傳值
    var contact : Contact?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        // 姓名
        let lab1 = UILabel(frame: CGRectMake(130, 100, 120, 30))
        lab1.backgroundColor = UIColor.orangeColor()
        lab1.text = contact?.name
        lab1.textAlignment = NSTextAlignment.Center
        view.addSubview(lab1)
        let lab11 = UILabel(frame: CGRectMake(50, 100, 70, 30))
        lab11.text = "name"
        view.addSubview(lab11)
        
        // 性別
        let lab2 = UILabel(frame: CGRectMake(130, 200, 120, 30))
        lab2.backgroundColor = UIColor.orangeColor()
        lab2.text = contact?.gender;
        lab2.textAlignment = NSTextAlignment.Center
        view.addSubview(lab2)
        let lab22 = UILabel(frame: CGRectMake(50, 200, 70, 30))
        lab22.text = "gender"
        view.addSubview(lab22)
        
        // 年齡
        let lab3 = UILabel(frame: CGRectMake(130, 300, 120, 30))
        lab3.backgroundColor = UIColor.orangeColor()
        lab3.text = contact?.age
        lab3.textAlignment = NSTextAlignment.Center
        view.addSubview(lab3)
        let lab33 = UILabel(frame: CGRectMake(50, 300, 70, 30))
        lab33.text = "age"
        view.addSubview(lab33)
        
        // 號(hào)碼
        let lab4 = UILabel(frame: CGRectMake(130, 400, 120, 30))
        lab4.backgroundColor = UIColor.orangeColor()
        lab4.text = contact?.phone
        lab4.textAlignment = NSTextAlignment.Center
        view.addSubview(lab4)
        let lab44 = UILabel(frame: CGRectMake(50, 400, 70, 30))
        lab44.text = "phone"
        view.addSubview(lab44)

        // Do any additional setup after loading the view.
    }

在 ViewController.swift 的延展 extension 中實(shí)現(xiàn)協(xié)議中的方法 didSelect 實(shí)現(xiàn)點(diǎn)擊 cell 跳轉(zhuǎn)到對(duì)應(yīng)聯(lián)系人詳情界面:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let detailVC = DetailViewController()
        
        detailVC.contact = ContactManager.shareIntance.contactArray[indexPath.row]
        
        detailVC.navigationItem.title = "聯(lián)系人詳情"
        
        navigationController?.pushViewController(detailVC, animated: true)
    }

運(yùn)行之后,點(diǎn)擊對(duì)應(yīng)的 cell 界面效果如下:


聯(lián)系人詳情界面

接下來(lái)鋪放添加聯(lián)系人界面

//
//  AddViewController.swift
//  Swift03-1
//
//  Created by 奇二世界 on 16/6/14.
//  Copyright ? 2016年 YMN. All rights reserved.
//

import UIKit

class AddViewController: UIViewController {
     ?// 懶加載textField
    lazy var tf:UITextField = {
        var tf = UITextField(frame:CGRectMake(130, 100, 100, 30))
        tf.borderStyle = UITextBorderStyle.RoundedRect
        tf.placeholder = "請(qǐng)輸入姓名"
        return tf
    }()
    
    lazy var tf2:UITextField = {
        var tf2 = UITextField(frame:CGRectMake(130, 200, 100, 30))
        tf2.borderStyle = UITextBorderStyle.RoundedRect
        tf2.placeholder = "請(qǐng)輸入性別"
        return tf2
    }()
    
    lazy var tf3:UITextField = {
        var tf3 = UITextField(frame:CGRectMake(130, 300, 100, 30))
        tf3.borderStyle = UITextBorderStyle.RoundedRect
        tf3.placeholder = "請(qǐng)輸入年齡"
        return tf3
    }()
    
    lazy var tf4:UITextField = {
        var tf4 = UITextField(frame:CGRectMake(130, 400, 100, 30))
        tf4.borderStyle = UITextBorderStyle.RoundedRect
        tf4.placeholder = "請(qǐng)輸入號(hào)碼"
        return tf4
    }()
    
    lazy var btn1:UIButton = {
        var b1 = UIButton(frame: CGRectMake(120, 500, 50, 30))
        b1.backgroundColor = UIColor.brownColor()
        b1.setTitle("取消", forState: UIControlState.Normal)
        b1.addTarget(self, action: "cancelAction:", forControlEvents: UIControlEvents.TouchUpInside)
        return b1
    }()
    
    lazy var btn2:UIButton = {
        var b2 = UIButton(frame: CGRectMake(200, 500, 50, 30))
        b2.backgroundColor = UIColor.brownColor()
        b2.setTitle("保存", forState: UIControlState.Normal)
        b2.addTarget(self, action: "addAction:", forControlEvents: UIControlEvents.TouchUpInside)
        return b2
    }()
    
    // 取消方法:點(diǎn)擊 取消 之后,不做任何操作,直接跳轉(zhuǎn)到主界面
    func cancelAction(btn:UIButton){

        navigationController?.popToRootViewControllerAnimated(true)
    }
    
    // 添加方法
    func addAction(btn:UIButton){
            let contact = Contact(name:tf.text!, gender:tf2.text!, age:tf3.text!, phone:tf4.text!)
            ContactManager.shareIntance.contactArray.append(contact)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        // 添加button
        view.addSubview(btn1)
        view.addSubview(btn2)
        // 創(chuàng)建提示標(biāo)簽
        let lab11 = UILabel(frame: CGRectMake(50, 100, 70, 30))
        lab11.text = "name"
        view.addSubview(lab11)
        
        view.addSubview(tf)
        
        let lab22 = UILabel(frame: CGRectMake(50, 200, 70, 30))
        lab22.text = "gender"
        view.addSubview(lab22)
        
        view.addSubview(tf2)
        
        let lab33 = UILabel(frame: CGRectMake(50, 300, 70, 30))
        lab33.text = "age"
        view.addSubview(lab33)
        
        view.addSubview(tf3)
        
        let lab44 = UILabel(frame: CGRectMake(50, 400, 70, 30))
        lab44.text = "phone"
        view.addSubview(lab44)
        
        view.addSubview(tf4)

        // Do any additional setup after loading the view.
    }

在 ViewController.swift 的 viewDidLoad() 中,添加 UIBarButtonItem 進(jìn)行界面跳轉(zhuǎn):

navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addAction:")

實(shí)現(xiàn)對(duì)應(yīng)的點(diǎn)擊方法 addAction:

func addAction(btn:UIBarButtonItem){
        let addVC = AddViewController()
        addVC.navigationItem.title = "添加聯(lián)系人"
        // 進(jìn)行界面跳轉(zhuǎn)
        navigationController?.pushViewController(addVC, animated:true)
    }

這一步之后,點(diǎn)擊“保存”之前,一定要在 ViewController.swift 文件中 實(shí)現(xiàn) viewWillAppear 方法,在視圖即將出現(xiàn)之前 刷新 UI 界面,才能看到我們添加的聯(lián)系人,代碼如下:

// viewWillAppear 視圖即將出現(xiàn)
    override func viewWillAppear(animated: Bool) {
        super.viewDidAppear(animated)
        tableView.reloadData()        
    }

運(yùn)行效果界面圖,及點(diǎn)擊保存之后的界面效果如圖:


添加聯(lián)系人界面

點(diǎn)擊“保存”后的效果

最后一步就是實(shí)現(xiàn)滑動(dòng) cell 的刪除功能,點(diǎn)擊"Delete"之后,該對(duì)應(yīng)的 cell 就在主界面上被刪除了。:
在 ViewController.swift 的 延展 中,實(shí)現(xiàn)協(xié)議中的方法:

// 刪除cell方法:
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete
        {    
        ContactManager.shareIntance.removeContactByIndexPath(indexPath)            
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
    }

刪除效果如圖:


刪除效果界面

以上就是用 swift 實(shí)現(xiàn)的通訊錄中添加、刪除聯(lián)系人的簡(jiǎn)單功能,瑕疵比較多,共勉。

最后編輯于
?著作權(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)容