I had a situation just like that, when I create a GMSMapViewDelegate separate from my view controller.
What I did and you could try:
- Create a class that extends NSObject and the MKMapViewDelegate. (The delegate needs to conform to NSObjectProtocol)
- You need to create and setup the mapView in the new class, but let the view controller access it.
- ATTENTION - remember to maintain a reference to your new class in the view controller. The delegate is a weak variable in the 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)
}
(Added 02/08/2018)
PS
As mentioned by Chanchal Raj "MapView is a UI component, it shouldn't be in ViewModel class". It was my solution at the time but it's not the correct way, conceptualy speaking (using MVVM).