【问题标题】:What is the best way to approach a 'How many items do you have selected' type counter?处理“您选择了多少项目”类型计数器的最佳方法是什么?
【发布时间】:2021-09-18 11:38:23
【问题描述】:

我的意思是:我有一个表格视图和填充单元格,我希望每个单元格在被选中时链接到其布尔值表示的打开或关闭状态。当它处于“开启”状态时,它会向计数器添加 +1,当它被点击到它的“关闭”状态时,它会收回该计数(因此减去)。我在填充表格视图的类中有 b​​ool,这样在通过搜索栏过滤数据时它不会混淆选择

想象一下“您选择了多少项目”类型的计数器。

我不确定的是如何将 bool 连接到选择本身,这样它就不会“混淆”。欢迎举例!

谢谢

【问题讨论】:

  • 您应该有一个数据源,它是一个自定义对象的数组(例如,[Item])。每个对象(可以是结构或类,没关系)可以包含一个Bool,表示它是on 还是off。然后在触发切换时设置此状态(尝试using closures)。

标签: arrays swift xcode checkbox switch-statement


【解决方案1】:

可能最简单的解决方案是使用简单的变量“计数器”并在 UITableViewDelegate 方法 didSelectRowAt(向上计数)和方法 didDeselectRowAt(向下计数)中计算您的选择

以下是一些步骤和示例代码:

  1. 创建UITableview 并使您的UIViewController 符合UITableViewDelegate 协议。然后将方法添加到您的 UIViewController 并符合 yourTableView.delegate = yourViewController(可能只是自己)。

添加委托方法:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.counter += 1
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    self.counter -= 1
}

【讨论】:

  • 你好,这个很简单,效果很好,我唯一需要添加的就是这行代码支持多选 self.tableView.allowsMultipleSelection = true
  • @RemBithsWind 我很高兴能帮上忙。 :)
  • @RemBithsWind 嗨,我看到昨天我的答案已从“已接受”中删除,答案有问题吗?谢谢
  • @RemBithsWind 我了解,但是 searchBar 的实施不是您最初问题的一部分..
  • @RemBithsWind 谢谢。无论如何,实现searchBar 的更好方法是将选择/取消选择的布尔值存储在项目本身中,如果(如您所做)然后在cellForRowAt indexPath: 方法中选择/取消选择单元格。也不要忘记取消选择所有单元格,一旦您的用户开始搜索
【解决方案2】:

要解决这个问题,我将有一个自定义表格视图单元格。一个很棒的教程在这里:https://www.youtube.com/watch?v=OQYqGM5_wVY&list=LL&index=16&t=752s 它实际上显示了在 tableview 中使用 switch。

为了有一个计数器,我会使用 UINotification Center。在自定义 tableview 单元格 swift 文件中,我会在您的开关操作中添加类似于以下代码的内容:

if switch.isOn{
   NotificationCenter.default.post(Notification(name: Notification.Name("tableSwitchClicked"), object: nil, userInfo: ["isOn":true]))
} else {
   NotificationCenter.default.post(Notification(name: Notification.Name("tableSwitchClicked"), object: nil, userInfo: ["isOn":false]))
}

“switch”是您的交换机的插座名称。 然后将其添加到 viewDidLoad 中的 viewcontroller swift 文件中:

NotificationCenter.default.addObserver(self, selector: #selector(changeSwitchCounter(_:)), name: Notification.Name("tableSwitchClicked"), object: nil)

最后,在主视图控制器中 viewDidLoad 之后的代码中:

@objc func changeSwitchCounter(_ notification: Notification){
   let positiveChange = notification.userInfo!["isOn"] as! Bool
   if positiveChange == true {
      switchOnCount += 1
   } else if positiveChange == false {
      switchOnCount -= 1
   }
   
}

其中 switchOnCount 是用于跟踪开关量的变量。我希望这可以帮助你!如果您有任何问题,请发表评论。

【讨论】:

    猜你喜欢
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2016-05-26
    • 2022-10-09
    • 1970-01-01
    相关资源
    最近更新 更多