Swift - 从另一个 class 访问 mapView 时遇到问题
Swift - trouble with accessing mapView from another class
我想通过属于tableView 单元格的按钮在地图上设置位置。问题是,如何获取我的 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)
}
}
但结果出现以下错误
我想整个事情是关于访问 ViewController 实例而不是创建一个全新的实例(如果我错了请纠正我)。
非常感谢任何帮助,在此先感谢
您调用的不是 ViewController
的实际实例,而是 class 本身。然而,map
是 ViewController
实例的成员。要解决这个问题,您必须在相应的实例上调用 map
。
这可以通过例如回调来完成。例如。在CustomCell
定义一个变量:
var onMapButtonCallback : ((CLLocationCoordinate2D) -> Void)?
然后您可以从 mapButton
:
执行
@IBAction func mapButton(sender: AnyObject) {
onMapButtonCallback?(Location)
}
剩下要做的是连接 ViewController
中的回调,我假设它也会实例化 CustomCell
:
customCell.onMapButtonCallback = { location in self.showPinOnMap(location) }
我想通过属于tableView 单元格的按钮在地图上设置位置。问题是,如何获取我的 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)
}
}
但结果出现以下错误
我想整个事情是关于访问 ViewController 实例而不是创建一个全新的实例(如果我错了请纠正我)。
非常感谢任何帮助,在此先感谢
您调用的不是 ViewController
的实际实例,而是 class 本身。然而,map
是 ViewController
实例的成员。要解决这个问题,您必须在相应的实例上调用 map
。
这可以通过例如回调来完成。例如。在CustomCell
定义一个变量:
var onMapButtonCallback : ((CLLocationCoordinate2D) -> Void)?
然后您可以从 mapButton
:
@IBAction func mapButton(sender: AnyObject) {
onMapButtonCallback?(Location)
}
剩下要做的是连接 ViewController
中的回调,我假设它也会实例化 CustomCell
:
customCell.onMapButtonCallback = { location in self.showPinOnMap(location) }