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

标签 ios swift mvvm mapkit

在我的 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/

相关文章:

c# - 如何处理检索 i2c 缓冲区和设置模型/实体属性?

javascript - 从 JavaScript 从 WKWebView 中的 iOS tmp/文件夹加载图像文件

ios - 看到其他玩家 nextpeer

ios - Instagram/tags/\(hashtag)/media/recent 端点不返回分页?

iOS:如何使用 RxSwift 删除 TableView 中的单元格

wpf - Prism with MVVM - 如何从外壳激活加载模块中的 View

c# - 如何在 XAML 中创建 "Window"菜单?

objective-c - 从 indexPath/Swip Gesture 获取单元格名称

ios - iBeacon 在后台测距?

ios - 我的 TableViewController 中的filteredUsers 的数据源应该是什么?