ios - Swift - 从另一个类访问 mapView 时遇到问题

标签 ios swift mkmapview viewcontroller

我想通过属于 tableView 中单元格的按钮在 map 上设置位置。问题是,如何获取我的 ViewController 的当前时刻而不是创建一个新的?我的CustomCell中的方法如下:

@IBAction func mapButton(sender: AnyObject) {
        ViewController().showPinOnMap(Location)
    }
} 

我最终得到的 mapView 等于 nil,我猜是因为我实例化了新的 ViewContoller 而不是访问已经存在的 ViewContoller。 我读过类型方法,但我不确定如何处理它们。在我的 ViewController 中,我尝试了:

class func showPinOnMap(location: CLLocationCoordinate2D?){
    if(location != nil){
        map.setCenterCoordinate(location!, animated: true)
    }
}

但结果出现以下错误 enter image description here

我想整个事情是关于访问 ViewController 实例而不是创建一个全新的实例(如果我错了请纠正我)。

如果有任何帮助,我将不胜感激

最佳答案

您调用的不是 ViewController 的实际实例,而是类本身。然而,mapViewController 实例的成员。要解决这个问题,您必须在相应的实例上调用 map

例如,这可以通过回调来完成。例如。在 CustomCell 中定义一个变量:

var onMapButtonCallback : ((CLLocationCoordinate2D) -> Void)?

然后您可以从 mapButton 执行:

@IBAction func mapButton(sender: AnyObject) {
    onMapButtonCallback?(Location)
} 

剩下要做的是在 ViewController 中连接回调,我假设它也会实例化 CustomCell:

customCell.onMapButtonCallback = { location in self.showPinOnMap(location) }

关于ios - Swift - 从另一个类访问 mapView 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28070462/

相关文章:

ios - 完成的 Firebase 嵌套查询

iOS/swift : SecItemCopyMatching yields errSecParam (-50) status for access control of biometryCurrentSet

ios - 返回 TableView 后 TableView 重新加载行

swift - 如何在 RealityKit 中使用 Raycast 方法?

ios - 导航 Controller 无法正常工作

ios - 你如何阻止 UIWindow 剪裁到旋转边界并显示 'black frame' ?

iOS Metal 计算管道比搜索任务的 CPU 实现慢

ios - 添加具有比例宽度的 subview 到 ScrollView

ios - Swift 3 - 每次添加位置坐标时 UIView 都会加载

iphone - 在注释 View 上使用 canShowCallout 时出现 MKMapKit 异常