2017-08-25 33 views
0

这是问题所在,当我使用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) 
    }) 

} 

first one identical one

+0

请澄清的问题。要求调试帮助的问题需要包含导致问题的代码,预期行为和实际行为。 –

+0

请在代码中使用if方法,然后检查。 – Mehul

+0

@Mehul谢谢,应用程序现在没有崩溃,但仍然显示两次相同的行为 –

回答

1

从 'cellForRow' 方法移动动画'willDisplayCell'方法。我认为它可以帮助你避免两次动画。

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) 
    } 
} 

I have fixed it