什么时候在看不到函数调用的程序中调用快速函数?

时间:2019-03-19 10:12:53

标签: ios swift mapbox mglmapview

The example below来自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
  }
}

3 个答案:

答案 0 :(得分:2)

这些是由称为MGLMapViewDelegate的协议声明的委托方法,该协议已实现到您的类

class ViewController: UIViewController, MGLMapViewDelegate { ... }

通过将某个对象的delegate设置为控制器(= self),就像在MGLMapView中使用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)
        ...
    }
}

答案 1 :(得分:0)

npm i country-state-city

使用

mapView.delegate = self

负责调用它们,在 MapKit 框架内,当您在内部设置正确的委托时,类class ViewController: UIViewController, MGLMapViewDelegate { 具有委托属性

MKMapView

您也不应该在这里返回nil

delegate?.mapView(self,//)

答案 2 :(得分:0)

它们是委托函数,而不是您调用的普通函数,更像是基于操作被调用的函数,并且您确实将MapView.delegate设置为self,因此当在MapView关于调用他们的情况,他们将回到您的self的已实现方面,在这种情况下为UIViewController,我建议阅读有关委托人here的更多信息,因此捷径答案是,函数不在同一类中调用。