用户默认保存mapType UISegmentedControl

时间:2018-07-22 11:33:56

标签: swift mkmapview uisegmentedcontrol

我需要将MapView地图类型保存在UISegmentedControl中。该代码仅将所选地图类型保存在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
        }
}

1 个答案:

答案 0 :(得分:1)

使其具有功能,并在viewDidLoad和操作中对其进行调用

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()
       }
}