打开应用程序时如何保存UISwitch状态(打开或关闭)? (SWIFT)

问题描述 投票:0回答:1

我设置了一个视图控制器,该控制器从我的初始视图控制器中弹出,并在此新视图控制器中设置了一个表视图,该表视图的每个单元格都填充了我创建的数组(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
1个回答
0
投票

您可以在应用程序中使用Coredata或UserDefaults来存储数据,否则,每次打开应用程序或关闭视图时,应用程序中的数据都会被重置。您可以创建一个UserDefaults来存储阵列,并在每次需要时通过UserDefaults访问阵列。

将数组存储在UserDefaults中

UserDefaults.standard.set(["your array here"], forKey: "set a key to access your array here")

要访问您的阵列

UserDefaults.standard.array(forKey: "the key you set when setting the array")

您还可以执行类似的操作来存储开关的状态。

© www.soinside.com 2019 - 2024. All rights reserved.