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

标签 ios iphone swift swift2

我正在学习 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/

相关文章:

iphone - 单击按钮时如何增加标签值

javascript - add/removeClass 在 iPhone 上不起作用

ios - 同一个 UIView 中的多个 UIPickerView

ios - Swift 使用 NSFetchedResultsController 和 UISearchBarDelegate

ios - 如何在 swift 中使用 NSCoder 对字符进行编码?

iOS 7.0 UITextView 在添加图像后变得非常慢

android - 我可以同时使用 Parse 和 Firebase 吗?

ios - UICollectionView 显示每个部分的滚动指示器(标题 zIndex 损坏)

iphone - 在 UITabBarController 的标签栏上显示 UIView

ios - 在另一个导航 Controller 上弹出导航 Controller