ios - 从 ViewController 向 View 传递数据时如何设置委托(delegate)?

标签 ios swift delegates protocols

相关代码如下:

在 View Controller 中

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)
 }

}

这行不通。 “位置”总是被保存为空,我相信这是因为我没有设置委托(delegate)。我知道这通常是在两个 ViewController 之间传递数据时在 prepareForSegue 中完成的,但在这种情况下,我不确定何时设置它。我该怎么办?

最佳答案

我认为您对委托(delegate)模式的工作原理感到困惑。

如果我理解您正在尝试做什么...在 ViewController 中,您正在接受对 mapView 的长按,这也传递了 CLLocationCoordinate2D。然后您创建一个 CreatePostView,您希望将其作为 subview 添加到您的 View 中...并且您希望在该 createPostView 中设置 location var > 实例到长按坐标。正确吗?

如果是这样,您根本不需要委托(delegate)。

相反,您的 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 有文本字段和按钮,并且您希望将那些值“向上”传递给您 View Controller 。

关于ios - 从 ViewController 向 View 传递数据时如何设置委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358573/

相关文章:

objective-c - 为 NSXMLParser 设置委托(delegate),给出 SIGABRT 错误

c# - 为 generi 方法抛出的 'Common Language Runtime detected an invalid program.' 异常需要解决方法

ios - 将实体的自定义字段与 NSPredicate 一起使用

ios - Segue 后页面 View 大小不正确

Swift (iOS 8 SDK) 将 Unmanaged<ABMultiValueRef> 转换为 ABMultiValueRef

swift - SKSpriteNode - 中断 animateWithTextures 后纹理未恢复到原始大小

ios - 如何在 ViewController 之间传递委托(delegate)

iphone - 使用UINib时看不到

iphone - Google AdMob 未在 iphone sdk 中显示广告

ios - 带有 Segue 的 UISearchbar (UISearchResultsUpdating) 仍然可见