swift之UITableView的使用

原文地址:http://www.wugaojun.com/blog/2015/05/09/ru-he-da-jian-bo-ke/

1.创建tableView

Swift和OC中UITableView的使用基本是差不多,只是有一些语法上的差异。下面我们一步一步从0开始写一个tableView。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import UIKit  let ID = "Cell" //cell的ID,建议像这样写一个常量,不要直接使用"Cell"  class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { //0.遵守协议   override func viewDidLoad() {  super.viewDidLoad()   //1.创建UITableView(跟OC几乎一样)  var tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Plain)   //2.注册Cell  tableView.registerClass(UITableViewCell.self,0)!important">forCellReuseIdentifier: ID)  //下面这种写法也是可以的  //tableView.registerClass(UITableViewCell.classForCoder(),forCellReuseIdentifier: ID)   //3.设置数据源和代理  dataSource = self  delegate = self;   //4.添加到view中  self.addSubview(tableView)  } } 

注意:1.协议的写法,不需要写<>。2.上面的代码中第0步和第3步会报错,不要惊慌,暂时无视,并不是代码有问题,是因为我们没有实现相应的协议方法

2.准备假数据

11
// 懒加载 lazy var datas: [Int] = {  // 创建一个存放int的数组  nums = [Int]()  // 添加数据  for i in 0...50 {  nums.append(i)  }  // 返回  return nums }() 

这里采用懒加载,Swift的懒加载和OC差别还是比较大的,需要注意一下。

3.实现协议方法

17
// MARK: - UITableViewDataSource & UITableViewDelegate  tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {  //返回有多少行Cell,这里返回数组的count  datas.count }  cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {  // 获得cell  cell = dequeueReusableCellWithIdentifier(ID,0)!important">forIndexPath: indexPath) as! UITableViewCell   // 配置cell  cell.textLabel!.text = "假数据 - \(datas[indexPath.row])"   // 返回cell  cell } 

解释几个可能有点迷糊的地方:

  1.as:这个东西比较符合人类思维。意思就是把什么当作什么,在上面的代码中,由于方法dequeueReusableCellWithIdentifier的返回值是AnyObject(也就是OC中的id类型),所以需要通过as告诉编译器这实际上是一个UITableViewCell。

  2.!(感叹号):这玩意就是告诉编译器我确定这里的的cell.textLabel一定是非nil的,可以放心的执行后面的。as后面的!也是一样的道理。

至此,可以编译运行看看效果了.

4.增加左滑删除功能

实现一个方法即可

11
// 提交编辑操作 func commitEditingStyle editingStyle: UITableViewCellEditingStyle,   forRowAtIndexPath indexPath: NSIndexPath) {  // 如果是删除操作  if editingStyle == .Delete {  // 从数组中移除对应位置的数据  removeAtIndex(indexPath.row)  // 删除表格中对应行的数据  deleteRowsAtIndexPaths([indexPath],0)!important">withRowAnimation: UITableViewRowAnimation.Fade)  } } 

大功告成,运行看看效果吧。

Done!

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...