UITableViewCell的重用机制是个非常强大的功能,但是有时候也会带来很大麻烦,比如说重叠,如图所示:
本来是这样的:
可是上下滚动几下之后就会变成这样!!
cell里面所有的东西都变粗了好几倍!
然后点快照看看:
里面已经有N个cell在开party了:
原因是UITableViewCell重用了,而我这个时候并不需要这种重用。
我用过的有效的有两种方法:
第一种:
新建一对.swift和.xib文件当作UITableViewCell用
记得设置reuseIdentifier
使用的时候
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
self.tableView.register(UINib(nibName:"myTableViewCell",bundle:nil), forCellReuseIdentifier: "myTableViewCell")
let myCell:myTableViewCell = tableView.dequeueReusableCell(withIdentifier: "myTableViewCell") as! myTableViewCell
/*
myCell的一系列设置
*/
return myCell
}
第二种:
在UITableView的cellForRowAt代理方法里加上这两句:
let cellIdentifier = "cell"
cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: cellIdentifier)
即:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
/*加上以下两句, 如果有switch结构的话,要在每个case里加上这两句*/
let cellIdentifier = "cell"
cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: cellIdentifier)
/*
cell的相关设置
*/
return cell!
}
当然还有很多方法可以解决,比如删除重复的cell,但我还没有用过,也许以后会在这篇文章补充吧~