【问题标题】:Selecting and Deselecting UITableViewCells - Swift选择和取消选择 UITableViewCells - Swift
【发布时间】:2015-05-19 07:47:13
【问题描述】:

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

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


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

    tableView.deselectRowAtIndexPath(indexPath, animated: true)

}
  • 我的View Controller 中有一个TableView
  • dataSourcedelegate 已设置。
  • UIBuilder 中为表格启用了多项选择。

【问题讨论】:

  • 在这段代码中你想做什么?你得到当前点击的单元格,然后将 backgroundColor 设置为紫色。它的目的是什么,它是否有效?
  • 是的,我得到了当前点击的单元格并将背景设置为紫色,它运行良好。现在,我正在尝试再次点击该单元格并将其取消选择为我选择它之前的方式。

标签: ios uitableview swift didselectrowatindexpath


【解决方案1】:

更新了 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
 }

【讨论】:

    【解决方案2】:

    您是否尝试过创建一个简单的布尔值并在下一次点击中进行验证。如果它是真的,你使用下面的代码,否则你一直点击它直到你再次点击它

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

    【讨论】:

      【解决方案3】:

      我可以发誓我之前尝试过,但当时没有用。

      我决定使用两个函数..

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

      【讨论】:

      • 该死的,伙计!太感谢了。干杯。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 2013-02-26
      相关资源
      最近更新 更多