我试图使用此代码突出显示我的表格中的第一个单元格:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
cell.layer.borderWidth = 0
cell.layer.borderColor = nil
cell.layer.borderWidth = 2
cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
}
}
一切似乎还可以。但是,当我单击一些单元格时,转到另一个ViewController,然后返回到我的单元格,已经突出显示了第二个单元格。因此,我已经单击了几次单元格,并发现从另一个视图控制器返回tableview后,下一个单元格(n单击我的所有单元格之后)。
即使我回到另一个控制器并返回我的单元格,我应该如何修复我的代码以突出显示第一个单元格?
单元格被重复使用。当您为给定条件设置任何属性时,必须始终重置该属性的所有其他条件。
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
cell.layer.borderWidth = 2
cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
} else {
cell.layer.borderWidth = 0
cell.layer.borderColor = nil
}
}
您必须实现else
分支并在此添加单元格的默认渲染。
类似的东西:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
cell.layer.borderWidth = 2
cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
} else {
cell.layer.borderWidth = 0
cell.layer.borderColor = nil
}
}
此代码不应真正在您的视图控制器中。创建一个UITableViewCell
…
class myCell: UITableViewCell {
var hasBorder = false {
didSet {
layer.borderWidth = hasBorder ? 2 : 0
layer.borderColor = hasBorder ? UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor : nil
}
}
}
然后在您的cellForRow atIndexPath
方法中:
cell.hasBorder = indexPath.row == 0