以下是相关代码:
ViewController中的
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)
}
}
这不起作用。 "位置"总是被保存为空,我相信它是因为我没有设置代表。我知道这通常是在两个ViewController之间传递数据时在prepareForSegue中完成的,但在这种情况下,我不确定何时设置它。我应该怎么做呢?
答案 0 :(得分:2)
我认为您对委托模式的工作原理感到困惑。
如果我理解你要做什么......在ViewController
你接受mapView上的longPress,它也传递了CLLocationCoordinate2D
。然后,您要创建一个CreatePostView
作为子视图添加到视图中......并且您希望将该location
实例中的createPostView
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
包含文本字段和按钮,并且您希望传递那些值" up"那么您可能希望使用委托模式。到你的ViewController。
答案 1 :(得分:0)
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
createPostView = createViewFromNib() as! CreatePostView
createPostView.setLocation(coordinate: coordinate)
createPostView.center = SCREEN_CENTER_POSITION
self.view.addSubview(createPostView)
}