使用委托在三个视图控制器之间传递数据。我为两个要传递数据的视图控制器设置了委托,它们在MapViewController
内部传递给自己-MapViewController
将从两个VC接收数据。
我还向两个VC添加了weak var delegate: MapViewController?
-但以某种方式它仅适用于其中一个。
MapViewController:
var newStartItem: MKMapItem?
override func viewDidLoad() {
super.viewDidLoad()
searchVC = (storyboard?.instantiateViewController(withIdentifier: "SearchPanel") as! SearchResultTableViewController)
searchVC.delegate = self
newVC = (storyboard?.instantiateViewController(withIdentifier: "newLocation") as! NewLocationTableViewController)
newVC.delegate = self
...
}
func addStartAnnotationToMap() {
guard let item = newStartItem else { return }
guard let coordinates = item.placemark.location?.coordinate else { return }
addPin(title: item.name!, subtitle: "", coordinates: coordinates)
}
}
NewLocationViewController :(这不起作用)
class NewLocationTableViewController: UIViewController {
weak var delegate: MapViewController?
...
func passData() {
guard let mapItem = starts?.first else { return }
delegate?.newStartItem = mapItem
delegate?.addStartAnnotationToMap()
}
Xcode也不会返回任何错误!
答案 0 :(得分:2)
您应该声明一个协议:
protocol MapViewControllerDelegate: class {
func addStartAnnotationToMap()
}
然后将您的委托变量更改为:
weak var delegate: MapViewControllerDelegate?
并使MapViewController
符合MapViewControllerDelegate
协议,如下所示:
class MapViewController: UIViewController, MapViewControllerDelegate {
答案 1 :(得分:0)
您的代表必须是您协议类型的引用
在这种情况下:weak var delegate: MapViewControllerDelegate?
答案 2 :(得分:0)
为此
newVC = (storyboard?.instantiateViewController(withIdentifier: "newLocation") as! NewLocationTableViewController)
newVC.delegate = self
和
weak var delegate: MapViewController?
要工作,您需要验证在地图vc中的某个点上您是否提供了该位置vc,例如
self.present(newVC,animated:true,completion:nil)
或推动它,并打印出来以验证它是否为nil并且如果starts
为空,则保护不返回
func passData() {
print("delegate \(delegate) item \(starts?.first)")
guard let mapItem = starts?.first else { return }
delegate?.newStartItem = mapItem
delegate?.addStartAnnotationToMap()
}