如果我在MainView中创建mapView的实例,我如何在容器视图中使用该实例?
class MainView: UIViewController {
var mapView = MapView()
}
class ContainerView: UIViewController {
MainView.mapView.changeCameraPosition()
}
我怎么能访问这个mapView实例在容器视图或它是可能的?
在Burnsi和Rob的帮助下,我找到的解决方案是在将视图控制器添加到容器视图时将实例作为对象传递:
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)
和我也改变了类类型的容器视图和主视图在NextPageVC PassthruView,以便用户可以与地图交互时,容器视图控制器在顶部:
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
}
}
如果主视图有容器视图,那么场景将是这样的,如果我没有错:
class MainView: UIViewController {
var mapView = MapView()
var containerView = ContainerView()
}
如果是这种情况,你可以在ContainerView类中创建一个方法,该方法以MapView的一个对象作为参数,并在ContainerView(你在MainView类中拥有的ContainerView的对象)的MainView类中调用该方法。
方法可以是这样的:
private func changeCameraPosition(mapView: MapView) {
mapView.changeCameraPosition()
}
并在Main View类的containerView对象上调用这个方法:
containerView.changeCameraPosition(mapView: mapView)