【问题标题】:How to save a UISwitch state (on or off) when opening an app? (SWIFT)打开应用程序时如何保存 UISwitch 状态(打开或关闭)? (迅速)
【发布时间】: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


    【解决方案1】:

    您可以在您的应用中使用 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")
    

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

    【讨论】:

      【解决方案2】:

      [Bool] 添加到您的类中,数组计数为utilities.allFactions.count,您可以将此数组存储在UserDefaults 中。并在加载 tableView 时检索它。这是您需要的代码:

      var switchStates = [Bool]()
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
          if switchStates.isEmpty {
              switchStates = UserDefaults.standard.array(forKey: "switchStates") as? [Bool] ?? []
          }
          if switchStates.isEmpty {
              switchStates = (0..<utilities.allFactions.count).map { $0 == $0 }
              UserDefaults.standard.set(switchStates, forKey: "switchStates")
          }
          tableView.reloadData()
      }
      

      cellForRow:

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          // ...
          mySwitch.isOn = switchStates[indexPath.row]
          // ...
      }
      

      didChangeSwitch:

      @objc func didChangeSwitch(_ sender: UISwitch) {
          switchStates[sender.tag].toggle()
          UserDefaults.standard.set(switchStates, forKey: "switchStates")
          //...
      }
      

      【讨论】:

      • 我将该代码添加到我的类中,但是当我退出视图控制器并返回它时,所有开关都处于“开启”模式。我使用打印功能检查附加/删除功能是否已保存到数组中,但一切都恢复了默认值。
      • 您需要在切换操作中切换与 indexPath.row 对应的值。并保存。
      • 我也添加了didChangeSwitch部分,检查一下。
      • 太棒了!开关保持关闭!我现在遇到的唯一问题是它没有保存我的数组的状态。当我关闭开关时,我正在从数组中删除字符串,但是当我重新进入 VC 时,即使开关设置为“关闭”,应该删除的字符串仍然在数组中。
      • 这似乎是一个后续问题。你为什么不试着自己一步一步地解决这个问题呢?如果您觉得太难了,请在 SO 的完整详细信息中提出另一个问题并在此处评论链接,我会看一下并帮助您找出问题所在。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多