选择和取消选择UITableViewCells - Swift

时间:2015-03-17 01:05:03

标签: ios uitableview swift didselectrowatindexpath

目前我可以点按一个单元格并使用didSelectRowAtIndexPath选择它。但是,点击时我无法取消选择它。我希望切换这两个功能。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


    var selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
    selectedCell.backgroundColor = UIColor.purpleColor()

    tableView.deselectRowAtIndexPath(indexPath, animated: true)

}
  • TableView中有View Controller
  • 已设置dataSourcedelegate
  • 在表格UIBuilder中启用了多项选择。

3 个答案:

答案 0 :(得分:6)

我本来可以发誓我以前尝过这个并且它当时没有工作。

我决定使用两个函数..

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
    selectedCell.backgroundColor = UIColor.purpleColor()        
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    var deselectedCell = tableView.cellForRowAtIndexPath(indexPath)!
    deselectedCell.backgroundColor = UIColor.clearColor()
}

答案 1 :(得分:0)

你试过创建一个简单的bool并在下一次点击中验证。如果它是真的你使用下面的代码,你可以点击它直到你再次点击它

tableView.deselectRow(at:indexPath,animated:true)

答案 2 :(得分:0)

更新了Swift 3/4的代码语法

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let selectedCell = tableView.cellForRow(at: indexPath)
     currentCell.backgroundColor = UIColor.purple
 }

 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
     let deselectedCell = tableView.cellForRow(at: indexPath)
     currentCell.backgroundColor = UIColor.clear
 }
相关问题