gpt4 book ai didi

ios - 什么在我的 Swift 代码中调用 didUpdateLocations?

转载 作者:行者123 更新时间:2023-11-29 01:23:40 26 4
gpt4 key购买 nike

我正在学习 Swift,下面的代码片段中有一个 locationManager 方法。即使“定位我”按钮的操作代码中没有调用它,为什么我应该写这个?

import UIKit
import MapKit
import CoreLocation

class ViewController: `UIViewController, CLLocationManagerDelegate` {
@IBOutlet weak var Mapview: MKMapView!
var manager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(51.5078788, -0.08773210000003928)
let objectAnn = MKPointAnnotation()
objectAnn.coordinate = pinLocation
objectAnn.title = "London Bridge"
objectAnn.subtitle = "London, United kingdom"
self.Mapview.addAnnotation(objectAnn)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func Directions(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/maps?daddr=51.5078788,-0.08773210000003928")!)
}

@IBAction func LocateMe(sender: AnyObject) {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()

Mapview.showsUserLocation = true
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userlocation:CLLocation = locations[0] as CLLocation

manager.stopUpdatingLocation()

let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: location, span: span)

Mapview.setRegion(region, animated: true)
}
}

最佳答案

它被称为委托(delegate)。

您正在实现 CLLocationManagerDelegate

由于您使用此代码 manager.delegate = self 将您的 manager 委托(delegate)设置为 View Controller ,它将在特定条件下自动调用委托(delegate)事件。

在你的代码中,如果你的位置更新了, View Controller 会自动运行这个函数func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

关于ios - 什么在我的 Swift 代码中调用 didUpdateLocations?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34289477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com