The Tissot
The Tissot

Reputation: 95

How to use instance of API from Main View in Container View?

If i create an instance of mapView in MainView, how can i use that instance in Container View?

class MainView: UIViewController {

    var mapView = MapView()

}

class ContainerView: UIViewController {

    MainView.mapView.changeCameraPosition()

}

How can i access this mapView instance in container View or is it possible?

Upvotes: 0

Views: 56

Answers (2)

The Tissot
The Tissot

Reputation: 95

The solution i found and also with help from Burnsi and Rob is to pass the instance as an object when adding view controller to container view:

 let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
 let nextPageVC = storyboard.instantiateViewController(withIdentifier:"NextPage") as! NextPage
        nextPageVC.mapView = mapView
        addChild(nextPageVC)
        containerView.addSubview(nextPageVC.view)
        nextPageVC.view.frame = containerView.bounds
        nextPageVC.didMove(toParent: self)

And i also changed the class type of the Container View and Main View in NextPageVC to PassthruView so that users can interact with the map when Container View Controller is on top:

import Foundation
import UIKit

class PassthruView: UIView {
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // Get the hit view we would normally get with a standard UIView
        let hitView = super.hitTest(point, with: event)

        // If the hit view was ourself (meaning no subview was touched),
        // return nil instead. Otherwise, return hitView, which must be a subview.
        return hitView == self ? nil : hitView
    }
    
}

Upvotes: 1

Saifullah Fazlani
Saifullah Fazlani

Reputation: 16

If Main View has the Container View, then the scenario would be like this if I'm not wrong:

class MainView: UIViewController {
    var mapView = MapView()
    var containerView = ContainerView()
}

If that's the case, you can make a method inside ContainerView class that takes an object of MapView as a parameter and call that method inside MainView class on containerView (the object of ContainerView that you have in MainView class).

The method could be something like this:

    private func changeCameraPosition(mapView: MapView) {
      mapView.changeCameraPosition()
}

And call this method on containerView object in Main View class as:

containerView.changeCameraPosition(mapView: mapView)

Upvotes: 0

Related Questions