gpt4 book ai didi

ios - 如何在 MVVM 模型中使用 MKMapViewDelegate 方法

转载 作者:可可西里 更新时间:2023-11-01 01:02:57 25 4
gpt4 key购买 nike

在我的 View Controller 中,有一个 MKMapView 的导出,并且 View Controller 自然地符合 MKMapViewDelegate 来执行 MapKit 操作。

我正在尝试在项目取得进一步进展之前迁移到 MVVM 模型,以保持项目整洁。但是,我对如何将所有 MKMapViewDelegate 方法移动到 MKMapView 导出位于 View Controller 中的另一个文件一无所知。

谢谢。

附言我正在用 Swift 编码

最佳答案

当我创建一个独立于我的 View Controller 的 GMSMapViewDelegate 时,我遇到过这样的情况。

我做了什么,你可以试试:

  • 创建一个扩展 NSObject 和 MKMapViewDelegate 的类。 (委托(delegate)需要符合NSObjectProtocol)
  • 您需要在新类中创建和设置 mapView,但让 View Controller 访问它。
  • 注意 - 请记住在 View Controller 中维护对新类的引用。委托(delegate)是 map View 中的弱变量。

MapModelView.swift

class MapModelView:NSObject, MKMapViewDelegate {

let mapView:MKMapView!

init(screenSize: CGRect) {
// generate the map view at the size of the screen
// otherwise it won't be seen
self.mapView = MKMapView(frame: CGRectMake(0, 0, screenSize.width, screenSize.height)
super.init()
self.mapView.delegate = self
}
}

ViewController.swift

class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
// Get the screen size for the map view creation
let screenSize: CGRect = UIScreen.mainScreen().bounds

mapKitOperationsDelegate = MapKitOperations(screenSize: screenSize)
mapView = mapKitOperationsDelegate.getMapView()
view.addSubview(mapView)
}

(添加于 02/08/2018)

附言

正如 Chanchal Raj 所说,“MapView 是一个 UI 组件,它不应该在 ViewModel 类中”。这是我当时的解决方案,但从概念上讲,这不是正确的方法(使用 MVVM)。

关于ios - 如何在 MVVM 模型中使用 MKMapViewDelegate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com