0%

正确地创建UITableViewCell

最近有人问到关于cell的创建方面的问题,然后发现做得多之后反而有点乱了,于是重新整理了一下思路。

关于cell的重用方面的原理就不说了,网上一搜一大把。直接列一下具体的操作吧。

通常情况下,我们会通过以下三种方式创建cell。

1. 纯代码

假设我们从UITableViewCell派生出CodeCustomCell,并重写了对应的init方法:

1
2
3
4
5
6
7
8
9
10
11
class CodeCustomCell: UITableViewCell {

let centerLabel = UILabel()

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
centerLabel.text = "Code"
addSubview(centerLabel)
}

}

在Controller中用 registerClass() 方法向tableView注册其cell的信息:

1
2
3
4
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(CodeCustomCell.classForCoder(), forCellReuseIdentifier: cellID)
}

并在dataSource方法中获取即可:

1
2
3
4
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID)
return cell!
}

2. xib

派生出IBCustomCell,并在xib中完成拖拽之后,在 awakeFromNib() 中完成控件的定制:

1
2
3
4
5
6
7
8
9
10
class IBCustomCell: UITableViewCell {

@IBOutlet weak var centerLabel: UILabel!

override func awakeFromNib() {
super.awakeFromNib()
centerLabel.text = "Xib"
}

}

注意, 不能 在以下方法中对控件进行定制。因为这个时候控件还没被初始化。

1
init?(coder aDecoder: NSCoder)

在Controller中通过向 registerNib() 方法,注册其cell的信息:

1
2
3
4
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "IBCustomCell", bundle: nil), forCellReuseIdentifier: cellID)
}

并在dataSource方法中获取即可:

1
2
3
4
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID)
return cell!
}

3. storyboard

派生的类与xib的类似:

1
2
3
4
5
6
7
8
9
10
class SBCustomCell: UITableViewCell {

@IBOutlet weak var centerLabel: UILabel!

override func awakeFromNib() {
super.awakeFromNib()
centerLabel.text = "StoryBoard"
}

}

不同点在于cell在storyboard中的controller中进行配置:

往tableView中塞入一个cell,并设置其Class

和Identifier

最后直接在dataSource方法中获取即可:

1
2
3
4
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
return cell!
}

至于UICollectionViewCell,同理可得。

至此。