这是问题,当我使用TableViewController并在单元格上添加行为时被选中。行为显示两次
我该如何避免这种情况?
// MARK: - Table Deleget
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
UIView.animate(withDuration: 0.2, animations: {
cell?.viewWithTag(100)?.isHidden = true
(cell?.viewWithTag(200) as! UILabel).textColor = UIColor.red
})
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
UIView.animate( withDuration: 0.3, animations: {
cell?.viewWithTag(100)?.isHidden = false
(cell?.viewWithTag(200) as! UILabel).textColor = UIColor(red: 0, green: 128/255, blue: 128/255, alpha: 1)
})
}
答案 0 :(得分:1)
将动画从'cellForRow'方法移动到'willDisplayCell'方法。我认为它可以帮助你避免两次动画。
答案 1 :(得分:1)
我已修复它,添加一个var来记住已录制的单元格,并使用cellWillDisplay
刷新将显示的每个单元格,检查每个单元格是否已被选中,如果有,则显示所选单元格方式。
// MARK: - Table Deleget
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
index = indexPath.row
if let cell = tableView.cellForRow(at: indexPath){
UIView.animate(withDuration: 0.2, animations: {
cell.viewWithTag(100)?.isHidden = true
(cell.viewWithTag(200) as! UILabel).textColor = UIColor.red
})
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
UIView.animate( withDuration: 0.3, animations: {
cell.viewWithTag(100)?.isHidden = false
(cell.viewWithTag(200) as! UILabel).textColor = UIColor(red: 0, green: 128/255, blue: 128/255, alpha: 1)
})
}
}
// Added this
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let index = index, index == indexPath.row {
cell.viewWithTag(100)?.isHidden = true
(cell.viewWithTag(200) as! UILabel).textColor = UIColor.red
} else {
cell.viewWithTag(100)?.isHidden = false
(cell.viewWithTag(200) as! UILabel).textColor = UIColor(red: 0, green: 128/255, blue: 128/255, alpha: 1)
}
}