试图保存 SegmentController 的位置

trying to save the position of a SegmentController

我点击了一个分段控制器,然后它一次更改了 6 个具有不同值(公制到英制)的标签。

我有这个功能,但是当我切换到另一个页面并返回时,选择器重置为位置 0。有没有办法在我离开控制器并返回时保存所选位置。我说的是控制器,但它只有一个控制器,有很多 nib 文件,运行 就像一本书,所以当我翻页并返回时,它又回到了原来的位置。

我试过这段代码,可能视图确实出现了,但没有成功。

if measurementSwitch == 0 {
    metricImperialSwitch?.selectedSegmentIndex = 0
         print(measurementSwitch)
    }else {
        metricImperialSwitch?.selectedSegmentIndex = 1
        print(measurementSwitch)
    }

这是函数。

func P18Switch() {

        if metricImperialSwitch.selectedSegmentIndex == 0
        {
            measurementSwitch = 0
            CWLabel.text = "kg"; TWLabel.text = "kg"; CWaLabel.text = "cm"; TWaLabel.text = "cm"; CHLabel.text = "cm"; THLabel.text = "cm"
        }
        else if metricImperialSwitch.selectedSegmentIndex == 1
        {
            measurementSwitch = 1
            CWLabel.text = "st"; TWLabel.text = "st"; CWaLabel.text = "inch"; TWaLabel.text = "inch"; CHLabel.text = "inch"; THLabel.text = "inch"

        }
}

然后调用视图中的函数确实加载了。

您可以使用UserDefaults保存所选的段索引:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    UserDefaults.standard.set(metricImperialSwitch?.selectedSegmentIndex, "selectedIndex")
}



override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if UserDefaults.standard.value(forKey: "selectedIndex") != nil{
         measurementSwitch = UserDefaults.standard.value(forKey: "selectedIndex") as! Int
    }else{
         measurementSwitch = 0
    }
    if measurementSwitch == 0 {
         metricImperialSwitch?.selectedSegmentIndex = 0
    }
    else {
        metricImperialSwitch?.selectedSegmentIndex = 1
    }
    self.P18Switch()
}

UserDefaults 的替代方法是使用 Global Variables。这两种方法都很好,但最好使用 UserDefaults,因为即使应用程序完全关闭,这些值也会被保存。