iOS UITableView

UITableViewCell注册复用和不注册复用的问题

如果混淆注册Cell、不注册复用Cell,就会引起Cell的乱用。

不注册复用Cell

func dequeueReusableCell(withIdentifier: String) -> UITableViewCell?
Returns a reusable table-view cell object located by its identifier.

使用带一个参数的dequeueReusableCell方法,返回UITableViewCell?(意味着创建cell可能为nil)
官方文档解释
Parameters
identifier
A string identifying the cell object to be reused. This parameter must not be nil.
重用Cell对象的标识字符串,不能为nil

Return Value
A UITableViewCell object with the associated identifier or nil if no such object exists in the reusable-cell queue.
返回一个关联标识符的cell对象的可选;如果不存在复用cell队列,返回nil

	var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
    if (cell == nil)
   	{
        cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: identifier)
    }

注册Cell

func dequeueReusableCell(withIdentifier: String, for: IndexPath) -> UITableViewCell
Returns a reusable table-view cell object for the specified reuse identifier and adds it to the table.

Declaration
func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell

Parameters
identifier
A string identifying the cell object to be reused. This parameter must not be nil.
indexPath
The index path specifying the location of the cell. Always specify the index path provided to you by your data source object. This method uses the index path to perform additional configuration based on the cell’s position in the table view.

Return Value
A UITableViewCell object with the associated reuse identifier. This method always returns a valid cell.

Discussion
Call this method only from the tableView(:cellForRowAt:) method of your table view data source object. This method returns an existing cell of the specified type, if one is available, or it creates and returns a new cell using the class or storyboard you provided earlier. Do not call this method outside of your data source’s tableView(:cellForRowAt:) method. If you need to create cells at other times, call dequeueReusableCell(withIdentifier:) instead.

Important

You must specify a cell with a matching identifier in your storyboard file. You may also register a class or nib file using the register(:forCellReuseIdentifier:) or register(:forCellReuseIdentifier:) method, but must do so before calling this method.

使用带两个参数的dequeueReuableCell,返回UITableViewCell,注意解释中cell对象添加到tableview中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
	let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
	return cell
}

tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier)//注册Cell
发布了51 篇原创文章 · 获赞 19 · 访问量 8281

猜你喜欢

转载自blog.csdn.net/WxqHUT/article/details/103490923