【问题标题】:Uncheck TableView all TableView Selections in Swift4在 Swift4 中取消选中 TableView 所有 TableView 选择
【发布时间】:2018-06-03 17:26:56
【问题描述】:

我已经搜索并没有看到解决方案:

  • 我有一个允许多选的 tableView
  • 我想在 Swift 中设置一个按钮,以允许同时清除所有选择。该按钮将位于与 TableView 不同的 viewController(UIViewController)上。可以使用协议和委托,还是需要单例?我希望它在单击按钮时更新。

几年前我在这里看到了 Dejan Skledar 的回答:UITableViewCell checkmark to be toggled on and off when tapped 和名为 resetChecks() 的函数似乎是我正在寻找的,但我无法让我为 Swift 工作而编写的内容。当我运行它时,它实际上并没有进入方法,然后当调用该方法时,它会因“意外找到 nil”而崩溃。拜托,谁能给点建议?谢谢。这是我写的:

func removeChecks() {
    for i in 0...grainTableView.numberOfSections - 1 {
        for j in 0...grainTableView.numberOfRows(inSection: i) - 1 {
            if let cell = tableView(grainTableView, cellForRowAt: [i,j]) as? UITableViewCell {
                cell.accessoryType == .none 
            }
        }
    }
}

【问题讨论】:

  • 这是一个非常。非常糟糕的方式。不要自己调用 tableView(_:cellForRowAt: 这样的数据源和委托方法。推荐的方法是在模型中保持selected 状态。然后在所有实例中将此属性设置为false 并重新加载表格视图。您的代码甚至试图更改效率很低的不可见单元格。
  • 小心 - 在您链接的问题中没有一个正确答案(尽管有所有投票)。
  • 我感谢所有建议,因为我正在学习,并且会根据那些更有知识的人的建议来改进。如果您愿意分享一些示例代码以帮助我更好地理解您的观点,我将不胜感激。了解如何调用和使用一些代码,尤其是对于 tableViews 对我来说是一个挑战。

标签: ios swift uitableview accessorytype


【解决方案1】:

当你呈现 currentVC 时从 preVC 发送对象

class currentVC:UIViewController {

    var delegate:PreVC?

 func removeChecks() {

   if let grainTableView = delegate?.tableView {
      for i in 0...grainTableView.numberOfSections - 1 {
          for j in 0...grainTableView.numberOfRows(inSection: i) - 1 {
              if let cell = tableView(grainTableView, cellForRowAt: [i,j]) as? UITableViewCell {
                cell.accessoryType == .none 
             }
          }
      }
   }
}

//

func removeChecks() {

   if let grainTableView = delegate?.tableView {

      delegate?.shouldClear = true

      grainTableView.reloadData()

   }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    相关资源
    最近更新 更多