在我的 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)
}
(于 2018 年 2 月 8 日添加)
PS
正如 Chanchal Raj 所提到的“MapView 是一个 UI 组件,它不应该在 ViewModel 类中”。这是我当时的解决方案,但从概念上讲(使用 MVVM),这不是正确的方法。
关于ios - 如何在 MVVM 模型中使用 MKMapViewDelegate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826319/