arrays - 如何根据 UISwitch 操作更新类中项目的值?

标签 arrays swift uitableview indexing uiswitch

我有如下所示的项目类:

struct Cur: Decodable {
    let id: String?
    let name: String?
    let symbol: String?
    let rank: String?
    let switchVal: Bool?
}

这个类填充一个数组,数组填充 UITableView。

这里是我如何访问 UISwitch 操作:

@IBAction func switchBtn(_ sender: UISwitch) {
    if sender.isOn {

        // See if user is in Search Mode
        if inSearchMode {

            // if user in search mode get the Cur from filtered array
            if let switchRank = filterCur.index(where: {$0.switchVal}) {
                print("This is the rank: \(filterCur[switchRank].rank!)")

            }

        } else {
            if let switchRank = Cur.index(where: {$0.switchVal}) {
                print("This is where it is: \(Cur[switchRank])")

            }
        }

    } else {
        // Handle deleting previously selected Curs

    }
}

为了让我找到数组中的哪个项目被打开/关闭,我必须让数组已经更新(项目 switchVal = true?)。但是,要更新数组,我需要知道触发了哪个项目的开关。

那么,我的错误在哪里呢?

谢谢

最佳答案

解决此问题的一种方法是通过将其分配给 tag 属性,为每个 UISwitch 提供 Cur 的索引。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    ...
    cell.switch.tag = indexPath.row
    ...
}

既然您现在知道每个开关都有索引,您可以通过使用开关的标签访问您的数组来获取该项目。

@IBAction func switchBtn(_ sender: UISwitch) {
    let index = sender.tag
    let cur = Cur[index]
}

关于arrays - 如何根据 UISwitch 操作更新类中项目的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46953432/

相关文章:

c - 任意长度的二维数组

ios - 单击时如何避免单元格分隔符消失

ios - 从滑动中排除一个单元格行以删除

ios - 当进入结果 View 并返回时,带有 UISearchController 的 UITableView 进入导航栏下方

arrays - <> 生成的数组大小?

c - 如何在C中打印字符数组,例如Java的 'Arrays.ToString(array)'?

swift - 无法转换类型的通用默认参数值

swift - "assignment to ' - 不可变值 '"的初始化的 'cell' 从未使用过;考虑用分配给 '_' 替换或删除它

ios - 在 iOS 中,选定的单元格应移动到 UITableView 的顶部

android - Firebase 从数据库中求和项目