Swift中UITableView的简单使用

时间:2023-03-09 03:34:48
Swift中UITableView的简单使用

Swift中的注释

使用"// MARK:- 注释内容",对属性或方法进行注释

使用"///注释内容"对属性或方法提供调用说明的注释

使用extension对同一个类中的相关方法进行划分.

extension类似于OC中的category,也是只能扩充方法,不能扩充属性

使用代码添加UITableView

  1. 使用懒加载属性,声明一个tableView
  • lazy var talbeView : UITableView = UITableView()
  • 将tableView添加到控制器的View中
    • view.addSubview(tableView)
  • 设置tableView的frame为控制器的大小
    • tableView.frame = view.bounds
  • 设置数据源,必须要实现两个方法,如果不实现编译器会报错
    • tableView.dataSource = self
  • 设置代理,代理方法均为可选方法,如果不实现也没有问题
    • tableView.delegate = self

注意:可以将以上步骤抽成一个方法setupUI(),并且写到ViewController的extension部分,这样可以增强阅读性.

tableView的数据源方法

tableView的数据源方法中,有两个必须实现的方法,如果不实现,编译器会报错.可以将数据源方法单独写到extension中.

必须实现的两个方法为:

  • numberOfRowsInSection
  • cellForRowAtIndexPath
// MARK:- tableView的数据源方法
// extension类似OC的category,也是只能扩充方法,不能扩充属性
extension ViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
} func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 1.创建cell
let CellID = "CellID"
var cell = tableView.dequeueReusableCell(withIdentifier: CellID) if cell == nil {
// 在swift中使用枚举: 1> 枚举类型.具体的类型 2> .具体的类型
cell = UITableViewCell(style: .default, reuseIdentifier: CellID)
} // 2.给cell设置数据
cell?.textLabel?.text = "测试数据:\((indexPath as NSIndexPath).row)" // 3.返回cell
return cell!
}
}

在使用代码创建cell的时候:

  1. 创建CellID,并且使用let声明
  • 使用var cell = table.dequeueResuableCell(withIdentifier: CellID),从缓存池中取cell
  • 判断是否能从缓存池中取cell,即判断cell是否为空
    • 如果为空,则使用UItableViewCell(style: .default, reuseIdentifier: CellID)为cell赋值
    • 在swift中使用枚举,可以有两种方式,一种是"枚举类型.具体的类型",一种是".具体的类型"
  • 设置cell上的数据
  • 返回cell

tableView的代理方法

tableView的代理方法均为可选的,用到的时候再去实现,也可以将代理方法单独写到extension中.

// MARK:- tableView的代理方法
// extension类似OC的category,也是只能扩充方法,不能扩充属性
extension ViewController : UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("点击了:\((indexPath as NSIndexPath).row)")
}
}