swift何时/如何调用用户创建的函数



我目前正在学习如何使用swift进行编码。我创建了一个应用程序,可以使用地图视图简单地显示用户的位置。

在这个代码块中,swift什么时候调用函数locationManager((?我似乎从未调用过这个函数,但它正在运行中的所有逻辑

import UIKit
import MapKit
class ViewController: UIViewController,
CLLocationManagerDelegate{

@IBOutlet weak var map: MKMapView!
@IBOutlet weak var AreaLbl: UILabel!
var locationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = (locValue.latitude) (locValue.longitude)")
let userLocation = locations.last
let viewRegion = MKCoordinateRegion(center: (userLocation?.coordinate)!, latitudinalMeters: 600, longitudinalMeters: 600)
self.map.showsUserLocation = true
self.map.setRegion(viewRegion, animated: true)

}

如果你有什么资源可以推荐学习swift,请告诉我!

首先,一个顺序点。在Swift中,函数的名称包括参数。您的函数未命名为locationManager()。它被命名为locationManager(_:didUpdateLocations:)(一个未命名的参数和一个名为"didUpdateLocations"的参数(

现在回答你的问题。

iOS和Mac操作系统非常常见地使用委托设计模式。在这种模式中,一个对象将自己设置为另一个对象的";代表";。这基本上意味着委托对象同意在电话旁等待来电。

当您是对象的委托时,您同意对可能发送给您的一组消息(或可能调用的函数(作出响应;符合协议";定义您需要响应的消息。其中一些消息可能是必需的,有些可能是可选的。

调用函数不是Swift,而是操作系统。特别是位置经理。

您的viewDidLoad()函数包括行locationManager.delegate = self

这就让你成为了位置经理的代理人。这意味着您符合CLLocationManagerDelegate协议。它告诉位置管理器您已经准备好接受来自该协议定义的位置管理器的消息(函数调用(。

当您这样做,然后您告诉位置管理器开始用线路locationManager.startUpdatingLocation()更新您的位置时,位置管理器将在将来检测到设备位置发生更改时开始调用locationManager(_:didUpdateLocations:)函数。

这是导致调用locationManager(_:didUpdateLocations:)函数的原因。

最新更新