ios - 什么时候在没有可见函数调用的程序中调用 swift 函数?
问题描述
下面的示例取自 Mapbox,并展示了如何使用注释在地图上标记位置。我知道在应用程序启动时会调用 viewDidLoad,这就是在 viewDidLoad 函数中运行所有内容的原因。
我不明白这个程序中的最后两个函数是如何被调用的(它们似乎都有名字 mapView)。我在 viewDidLoad 中看不到对它们的引用
import Mapbox
class ViewController: UIViewController, MGLMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Set the map’s center coordinate and zoom level.
mapView.setCenter(CLLocationCoordinate2D(latitude: 40.7326808, longitude: -73.9843407), zoomLevel: 12, animated: false)
view.addSubview(mapView)
// Set the delegate property of our map view to `self` after instantiating it.
mapView.delegate = self
// Declare the marker `hello` and set its coordinates, title, and subtitle.
let hello = MGLPointAnnotation()
hello.coordinate = CLLocationCoordinate2D(latitude: 40.7326808, longitude: -73.9843407)
hello.title = "Hello world!"
hello.subtitle = "Welcome to my marker"
// Add marker `hello` to the map.
mapView.addAnnotation(hello)
}
// Use the default marker. See also: our view annotation or custom marker examples.
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}
// Allow callout view to appear when an annotation is tapped.
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
}
解决方案
这些是由调用的协议声明的委托方法,这些方法已MGLMapViewDelegate
在您的类中实现
class ViewController: UIViewController, MGLMapViewDelegate { ... }
通过将delegate
某些对象设置为您的控制器(= self
),就像您对MGLMapView
in所做的那样viewDidLoad
mapView.delegate = self
您是说,当在mapView
的委托上调用某个方法时,将调用您已实现的方法mapView(_:viewFor:) -> MGLAnnotationView?
。
无论如何,您mapView
应该是实例变量,否则您将失去对它的引用
class ViewController: UIViewController, MGLMapViewDelegate {
var mapView: MGLMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView = MGLMapView(frame: view.bounds)
...
}
}
推荐阅读
- c# - Magento 1 站点中的 Oauth 启动失败
- python-3.x - tkinter 框架不随画布展开
- excel - VBA Range.Cells 未知方法或数据成员
- assembly - 由 inc BYTE PTR [rip+0xc] 引起的 SIGSEGV
- azure - 如何重新路由 Azure Active Directory,最终在循环中结束的身份验证?
- reactjs - 更改页面值时 Nativebase 选项卡不更改内容
- python - sklearn.utils.class_weight 抛出“类应该包括所有可以在 y 中的有效标签”错误
- css - 更改 SVG 中的路径元素
- flutter - 在 Flutter 中使用 native_contact_picker 以相反的顺序返回电话号码
- octobercms - 如何在十月 CMS 中使用模型工厂?