【问题标题】:swift - how to save switch, even I change TableViewsswift - 如何保存开关,即使我更改了 TableViews
【发布时间】:2018-08-27 11:55:15
【问题描述】:
import UIkit
// ViewController file
class ViewController: UITableViewController, UIViewController{

    @IBAction func aaaSwitch(_ sender: UISwitch) {
        if (sender.isOn == true)
        {
            ClickCounterA+=2
            UserDefaults.standard.set(aaaSwitch, forKey: "aaaSwitch")
            UserDefaults.standard.bool(forKey: "aaaSwitch")
            defaults.set(aaaSwitch, forKey: "aaaSwitch")
        }
        else
        {
            defaults.set(aaaSwitch, forKey: "aaaSwitch")
        }
    }

我更改了 tableview 中的 switch(aaaSwitch) 并移动到另一个 tableview。之后,我回到第一个tableview,switch就是我改变之前的语句。也就是说,我无法保存 switch 语句。

【问题讨论】:

  • 当我关掉开关时,即使我走到桌边,从查看开关返回到看开关,开关仍然是关闭的。我希望如果 switch 为 false,则将另一个表视图中的计数器减去两个。
  • 将状态保存在model

标签: ios swift uitableview nsuserdefaults uiswitch


【解决方案1】:

问题是您将 aaaSwitch 方法传递给 UserDefaults 集合调用。你想传入一个值,在本例中是一个布尔值。

UserDefaults.standard.set(sender.isOn, forKey: "aaaSwitch")

如果您真的想归档整个 UISwitch,则需要先将其转换为 NSData(并且您可能必须想出一个算法来这样做)。而且我认为没有必要这样做。当然你只是想保持它的开/关状态,所以使用上面的代码。

【讨论】:

    【解决方案2】:
    class ViewController: UITableViewController, UIViewController{
            @IBOutlet weak var aaaswitch: UISwitch!
            override func viewWillAppear(_ animated: Bool) {
                    aaaswitch.isOn = UserDefaults.standard.bool(forKey: "aaaSwitch")
            }
            @IBAction func aaaSwitch(_ sender: UISwitch) {
                if (sender.isOn == true)
                    {
                            ....
                    }
                    else
                    {
                            ....
                    }
                    UserDefaults.standard.set(sender.isOn, forKey: "aaaSwitch")
            }
     }
    

    【讨论】:

    • 我也想知道如何将TableView中的标签与ViewController连接起来。
    • 简单说明
    • 表格视图单元格中的标签无法使用控制键连接到 ViewController。
    • 你得到答案了吗?
    • 不,我没有。我知道 tableviewcontroller 中的标签无法连接到 ViewController,所以我试图连接 ViewController(不是表)中的标签,但我收到 SIGABRT 错误。
    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    相关资源
    最近更新 更多