如何在将数据从ViewController传递到View时设置委托?
下面是相关代码:如何在将数据从ViewController传递到View时设置委托?
在视图控制器
protocol LocationDelegate {
func setLocation(coordinate: CLLocationCoordinate2D)
}
var locationDelegate: LocationDelegate?
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
locationDelegate?.setLocation(coordinate: coordinate)
createPostView = createViewFromNib()
createPostView.center = SCREEN_CENTER_POSITION
self.view.addSubview(createPostView)
}
在CreatePostView
class CreatePostView: UIView, UINavigationControllerDelegate, LocationDelegate {
var location: CLLocation! = CLLocation()
func setLocation(coordinate: CLLocationCoordinate2D) {
self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
}
这是行不通的。 “位置”总是被保存为空,我相信这是因为我没有设置代表。我知道这通常在prepareForSegue中在两个ViewController之间传递数据时完成,但在这种情况下,我不确定何时设置它。我应该怎么做呢?
我认为你对委托模式的工作原理感到困惑。
如果我明白你想要做什么......在ViewController
你正在接受mapView上的longPress,它也通过CLLocationCoordinate2D
。然后,您创建一个CreatePostView
,您想要将其作为子视图添加到您的视图中,并且您希望将该createPostView
实例中的location
var设置为长按坐标。正确?
如果是这样,你根本不需要委托。
相反,你的CreatePostView
类应该有:
class CreatePostView: UIView, UINavigationControllerDelegate {
var location: CLLocation! = CLLocation()
func setLocation(coordinate: CLLocationCoordinate2D) {
self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
}
和你ViewController
类应该有:
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
// instantiate your CreatePostView
createPostView = createViewFromNib()
// set it's .center property
createPostView.center = SCREEN_CENTER_POSITION
// here is where you "pass in" the coordinate
createPostView.setLocation(coordinate: coordinate)
// add it to your view
self.view.addSubview(createPostView)
}
您可能需要使用如果委托模式,例如,您createPostView
有文字字段和按钮,并且您希望将这些值“向上”传递给您的ViewController。
谢谢!这工作。也感谢澄清。 –
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
createPostView = createViewFromNib() as! CreatePostView
createPostView.setLocation(coordinate: coordinate)
createPostView.center = SCREEN_CENTER_POSITION
self.view.addSubview(createPostView)
}
它没有工作; setLocation函数仍然没有被调用,并且位置不被保存。 –
尝试上面的编辑。你甚至不需要这个委托。 –
Where /你如何创建一个'CreatePostView'对象? –
CreatePostView是用户长按地图视图时创建的自定义视图。我如何称它为上面所示(这是一个XIB)。 –
一次只有其中之一吗? –