UITableView基础[ 1 ] 基本TableView的实现

介绍

UITableView是iOS中最常用的高级UI控件,UITableView对于大部分App都是不可或缺的组成部分,利用UITableView我们可以实现大部分列表视图的呈现,掌握UITableView的使用非常重要。

使用

设置代理、数据源

使用UITableView首先要在ViewController中实现UITableViewDataSource 与UICollectionViewDelegate中的部分必须实现的方法

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
...
}

在viewDidLoad方法中设置UITableViewDelegateUITableViewDataSource

override func viewDidLoad() {
        super.viewDidLoad()
        //设置代理、数据源
        tableView.dataSource = self
        tableView.delegate = self
        // Do any additional setup after loading the view.
    }

这个操作也可以在InterfaceBuilder中实现
《UITableView基础[ 1 ] 基本TableView的实现》

注册重用标记

重用标记推荐定义一个常量
let reuseIdentifier="reuseIdentifier"
如果要显示的cell属于基本cell,可以在viewDidLoad中注册cell与重用标记

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: reuseIdentifier)
    }

实现代理数据源方法

这个方法用来返回每个Section应该有多少个cell

   func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        
        //cellInfoArray为储存cell信息的数组,测试时也可直接返回一个字面量
        return cellInfoArray.count
    } 

这个方法用于返回索引值为index处的cell

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
        cell?.textLabel?.text = "第\(indexPath.row)个cell"
        return cell!
    }

上面的两个方法是使用UITableView必须实现的方法,只需这样步骤,一个最简单的UITableView就能呈现出来啦
《UITableView基础[ 1 ] 基本TableView的实现》

    原文作者:Hydrogen
    原文地址: https://segmentfault.com/a/1190000003849134
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞