9.使用UITableView来制作一个简易的联系人存储列表

前面我们讲过几个UITableView的使用小技巧, 现在让我们来看看怎么使用UITableView把我们输入的信息存储到CoreData中.


1.界面布局

1

2


2.实现代码

1.声明变量

class CoreDataTableViewController: UITableViewController { 
    // 1.设置一个用来存储数据的字符串数组 
    var names = [String]()
    override func viewDidLoad() { 
        super.viewDidLoad() 
        // 2.设置
        title = "Name"

        // 3.给UITextViewCell添加identifier为"Cell" 
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    } 
}

2.设置TableView

// 4.设置UITableView有多少组Cell 
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
     return 1
 } 

// 5.设置UITableViewCell有多少行 
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return names.count 
} 

// 6.设置UITableViewCell显示的内容 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    // 6.1获取indentfier为Cell的UITableViewCell 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell 

    // 6.2设置UITableViewCell每行显示的内容 
    cell.textLabel!.text = names[indexPath.row] 

    // 6.3返回UITableViewCell 
    return cell
}

3.添加UIBarButtonItem点击事件

// 7.点击添加按钮的事件 
@IBAction func addName(sender: UIBarButtonItem) { 

    // 7.1添加一个UIAlertController, 设置title, message以及Style 
    var alert = UIAlertController(title: "新名字", message: "添加一个新的名字", preferredStyle: UIAlertControllerStyle.Alert) 

    // 7.2添加UIAlertController的保存按钮 
    let saveAction = UIAlertAction(title: "保存", style: UIAlertActionStyle.Default) { (action :UIAlertAction!) -> Void in 
        // 7.2.1获取UIAlertController里的UITextField的文本内容 
        let textField = alert.textFields![0] as! UITextField 
        // 7.2.2往names添加textField所输入的内容 
        self.names.append(textField.text) 
        // 7.2.3刷新整个TableView 
        self.tableView.reloadData() 
    } 

    // 7.3添加UIAlertController取消按钮 
    let cancelAtion = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in 
    } 

    // 7.4往UIAlertController上添加一个UITextField输入框 alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in 
    } 

    // 往UIAlertController上添加按钮, 注意, 这是有顺序的 
    // 7.5往UIAlertController添加取消按钮 
    alert.addAction(cancelAtion) 

    // 7.6往UIAlertController添加保存按钮
    alert.addAction(saveAction)

    // 7.8显示当前的一个ViewController, 设置动画效果
    presentViewController(alert, animated: true, completion: nil)
}

3.最终效果

0


好了, 这次我们就讲到这里, 下次我们继续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值