【发布时间】:2020-09-30 02:28:07
【问题描述】:
我设置了一个从我的初始视图控制器模态弹出的视图控制器,并在这个新视图控制器中设置了一个表格视图,其中每个单元格都用我创建的数组 (allFactions) 中的字符串填充。此表格视图中的每个单元格还附加了一个开关。
我将每个开关设置为从 allFactions 数组中追加/删除,无论是打开还是关闭,但我似乎无法: 1. 永久修改数组(当我返回初始视图控制器时数组恢复默认值)。 2. 保存每个单元格中 UISwitch 的状态,以便在重新进入应用时保持打开或关闭。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return utilities.allFactions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Writes a new faction on every line of the table
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = utilities.allFactions[indexPath.row]
// Creates a switch that can be toggle "on" or "off"
let mySwitch = UISwitch()
mySwitch.tag = indexPath.row
mySwitch.addTarget(self, action: #selector(didChangeSwitch(_:)), for: .valueChanged)
mySwitch.isOn = true
// Adds the switch to the right side of the cell
cell.accessoryView = mySwitch
return cell
}
@objc func didChangeSwitch(_ sender: UISwitch) {
if sender.isOn {
// Append selected faction to myFactions
addFaction(utilities.allFactions[sender.tag])
} else {
// Remove selected faction from myFactions
removeFaction(utilities.allFactions[sender.tag])
}
}
【问题讨论】:
标签: swift save tableview uiswitch