最近有人问到关于cell的创建方面的问题,然后发现做得多之后反而有点乱了,于是重新整理了一下思路。
关于cell的重用方面的原理就不说了,网上一搜一大把。直接列一下具体的操作吧。
通常情况下,我们会通过以下三种方式创建cell。
1. 纯代码
假设我们从UITableViewCell派生出CodeCustomCell,并重写了对应的init方法:
1 | class CodeCustomCell: UITableViewCell { |
在Controller中用 registerClass() 方法向tableView注册其cell的信息:
1 | override func viewDidLoad() { |
并在dataSource方法中获取即可:
1 | func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { |
2. xib
派生出IBCustomCell,并在xib中完成拖拽之后,在 awakeFromNib() 中完成控件的定制:
1 | class IBCustomCell: UITableViewCell { |
注意, 不能 在以下方法中对控件进行定制。因为这个时候控件还没被初始化。
1 | init?(coder aDecoder: NSCoder) |
在Controller中通过向 registerNib() 方法,注册其cell的信息:
1 | override func viewDidLoad() { |
并在dataSource方法中获取即可:
1 | func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { |
3. storyboard
派生的类与xib的类似:
1 | class SBCustomCell: UITableViewCell { |
不同点在于cell在storyboard中的controller中进行配置:
往tableView中塞入一个cell,并设置其Class
和Identifier
最后直接在dataSource方法中获取即可:
1 | func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { |
至于UICollectionViewCell,同理可得。
至此。