简体   繁体   English

选择和取消选择UITableViewCells - Swift

[英]Selecting and Deselecting UITableViewCells - Swift

Currently I am able to tap a cell and select it using didSelectRowAtIndexPath . 目前我可以点击一个单元格并使用didSelectRowAtIndexPath选择它。 However, I am unable to deselect it when tapped. 但是,点击时我无法取消选择它。 I wish to toggle these two features. 我希望切换这两个功能。

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


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

    tableView.deselectRowAtIndexPath(indexPath, animated: true)

}
  • I have a TableView in my View Controller . 我在View Controller有一个TableView
  • The dataSource and delegate are already set up. dataSourcedelegate已经设置dataSource
  • Multiple selection is enabled in UIBuilder for the table. UIBuilder为表启用了多个选择。

I could have sworn I tried this before and it didn't work then. 我本来可以发誓我曾经尝试过这个,但之后就没用了。

I decided to use two functions.. 我决定使用两个函数..

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

have you tried to create a simple bool and verify in the next tap. 你试过创建一个简单的bool并在下一次点击中验证。 If its true you use the code bellow else you keep it tapped until you tap it again 如果它是真的你使用其他代码,你可以点击它直到你再次点击它

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

Updated Code Syntax for Swift 3 / 4 更新了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
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM