首页 > 解决方案 > 什么时候在没有可见函数调用的程序中调用 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
  }
}

标签: iosswiftmapboxmglmapview

解决方案


这些是由调用的协议声明的委托方法,这些方法已MGLMapViewDelegate在您的类中实现

class ViewController: UIViewController, MGLMapViewDelegate { ... }

通过将delegate某些对象设置为您的控制器(= self),就像您对MGLMapViewin所做的那样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)
        ...
    }
}

推荐阅读