我有如下所示的项目类:
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/