我有一些文本进入我在表格 View 单元格内创建的 UIlabels。当这些表格 View 单元格更新时,文本自身重叠,几乎就像以前的文本一样,那里没有被删除,就像这样:
代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! UITableViewCell
var nameLabel = UILabel(frame: CGRectMake(cell.frame.size.width * 0.040, cell.frame.size.height * 0.22, cell.frame.size.width * 0.735, cell.frame.size.height * 0.312))
var userAtIndexPath = finalMatchesBlurUser[indexPath.row]
nameLabel.text = userAtIndexPath.username.uppercaseString
cell.addSubview(nameLabel)
}
finalMatchesBlurUser
是从 Parses 数据库中获取的一个 PFUser,它将发生变化,当这种变化导致名称重叠时。
谁能指出为什么会这样?
最佳答案
每次更新 tableview 时,它都会检查队列以查看它是否可以重用一个单元格而不是初始化一个新单元格。在这种情况下,当它更新时,它在队列中有单元格,因此每次表更新时您都会添加一个新的标签 subview ,这会导致这种效果。在这种情况下,如果标签 subview 不存在,您应该只添加它。否则,只需更新该 subview 的文本即可。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! UITableViewCell
if let nameLabel = cell.viewWithTag(100) as? UILabel{
var userAtIndexPath = finalMatchesBlurUser[indexPath.row]
nameLabel.text = userAtIndexPath.username.uppercaseString
}
else{
nameLabel = UILabel(frame: CGRectMake(cell.frame.size.width * 0.040, cell.frame.size.height * 0.22, cell.frame.size.width * 0.735, cell.frame.size.height * 0.312))
nameLabel.tag = 100;
var userAtIndexPath = finalMatchesBlurUser[indexPath.row]
nameLabel.text = userAtIndexPath.username.uppercaseString
cell.addSubview(nameLabel)
}
return cell;
}
关于swift - 文本在表格单元格中重叠 SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320069/