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中实现
图片描述

注册重用标记

重用标记推荐定义一个常量
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就能呈现出来啦
图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值