Userdefaults 保存 mapType UISegmentedControl

Userdefaults to save mapType UISegmentedControl

我需要在 UISegmentedControl 中保存 MapView 地图类型。该代码仅将所选地图类型保存在 UISegmentedControl 中,而不是将地图类型保存在 MapView 中。这是我的代码:

@IBAction func standard(_ sender: UISegmentedControl) {

        switch maptypes.selectedSegmentIndex {
        case 0:
           self.mapView.mapType = .hybrid

             UserDefaults.standard.set(maptypes.selectedSegmentIndex, forKey: "selectedMapType")

        case 1:

            self.mapView.mapType = .standard
        UserDefaults.standard.set(maptypes.selectedSegmentIndex, forKey: "selectedMapType")

        case 2:

            UserDefaults.standard.set(maptypes.selectedSegmentIndex, forKey: "selectedMapType")
            self.mapView.mapType = .satellite
        default:
            break;
        }
    }
override func viewDidLoad() {
        super.viewDidLoad()

if let value = UserDefaults.standard.value(forKey: "selectedMapType"){
            let selectedIndex = value as! Int
            maptypes.selectedSegmentIndex = selectedIndex
        }
}

将其设为函数并在 viewDidLoad 和 action

中调用它
func shared () {

  switch maptypes.selectedSegmentIndex {
    case 0:
       self.mapView.mapType = .hybrid

         UserDefaults.standard.set(maptypes.selectedSegmentIndex, forKey: "selectedMapType")

    case 1:

        self.mapView.mapType = .standard
    UserDefaults.standard.set(maptypes.selectedSegmentIndex, forKey: "selectedMapType")

    case 2:

        UserDefaults.standard.set(maptypes.selectedSegmentIndex, forKey: "selectedMapType")
        self.mapView.mapType = .satellite
    default:
        break;
    }
}

//

@IBAction func standard(_ sender: UISegmentedControl) {

   shared()
}
override func viewDidLoad() {
        super.viewDidLoad()

       if let value = UserDefaults.standard.value(forKey: "selectedMapType"){
            let selectedIndex = value as! Int
            maptypes.selectedSegmentIndex = selectedIndex
            shared()
       }
}