swift - Userdefaults 保存 mapType UISegmentedControl

标签 swift mkmapview uisegmentedcontrol

我需要在 UISegmentedControl 中保存 MapView map 类型。该代码只是将所选 map 类型保存在 UISegmentedControl 中,而不是将 map 类型保存在 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()
       }
}

关于swift - Userdefaults 保存 mapType UISegmentedControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51464668/

相关文章:

ios - 我正在尝试在 Swift 中添加 MDCCard 以使用 Material Components 获取 Material Card View。错误 : No such module 'MaterialComponents.MaterialCards'

ios - 在 Swift 中转换 UTC 时间

ios - 单击按钮时无法播放一系列图像

iphone - 每秒用新坐标 Iphone 更新 mapview 注释

ios - 分割的UISegmentedControl自定义图片

ios - UISegmentedControl 图像突出显示 iOS 中的错误?

json - Swift 4 Decodable - 附加变量

iphone - 有可能知道 CLLocation 点是否在 MKCoordinateRegion 中?

ios kmlviewer 加载远程 url 而不是本地文件

iphone - iOS 将 UISegmentedControl 选择存储在 NSUserDefaults 中