ios - 委托(delegate)方法如何在 Swift 中工作?

标签 ios oop swift delegates cllocationmanager

<分区>


想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .

关闭 8 年前

我正在尝试学习如何将位置编程到应用程序中,而这整段代码让我对 locationManager 和委托(delegate)感到困惑。当您声明一个名为 locationManager 的函数时,我完全不明白发生了什么。你正在定义这个功能,locationManager,对吧?有2个参数。那么究竟是什么调用了这个locationManager?通过 Complete iOS Developer Course 时,他获取了这个 locationManager 片段并复制粘贴它,而没有解释复制和粘贴它时你在做什么背后的原理。是否有某行代码调用“locationManager(...)”?如果是这样,这是在哪里发生的?我的大脑一直在想,如果它是一个从父类(super class) CLLocationManagerDelegate 继承的函数,您是否必须重写它才能使其工作?您能否就委托(delegate)的具体工作方式给出一些直觉?

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {



@IBOutlet var myMap : MKMapView!

var manager:CLLocationManager!


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


    // Core Location
    manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()




}


func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {

    var userLocation:CLLocation = locations[0] as CLLocation

    var latitude:CLLocationDegrees = userLocation.coordinate.latitude

    var longitude:CLLocationDegrees = userLocation.coordinate.longitude

    var latDelta:CLLocationDegrees = 0.01

    var lonDelta:CLLocationDegrees = 0.01

    var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)

    var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)

    var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)

    myMap.setRegion(region, animated: true)

}

func locationManager(manager:CLLocationManager, didFailWithError error:NSError)
{
    println(error)
}

非常感谢您的帮助!

最佳答案

这些委托(delegate)方法,定义在 CLLocationManagerDelegate 中协议(protocol),由您实例化并在 manager 变量中引用的 CLLocationManager 对象调用。因此,您已经实例化了 CLLocationManager 对象,您已要求它在有位置更新时通知您,它通过调用您已实现的这些委托(delegate)方法来实现这一点。

你说:

My brain keeps thinking that if it's a function that's inherited from a superclass, CLLocationManagerDelegate, wouldn't you have to override it in order to get it to work?

CLLocationManagerDelegate 不是一个类。这是一个“协议(protocol)”。它定义了委托(delegate)对象(在本例中为您的 View Controller )可以/应该实现哪些功能。所以,没有什么可以覆盖的。

关于ios - 委托(delegate)方法如何在 Swift 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27682805/

上一篇:ios - 无法关闭导航 Controller 中嵌入的两个 View Controller

下一篇:ios - 在 Xcode 6 中更改文件夹位置时无法构建

相关文章:

调用对象函数的javascript变量

c# - 在另一个文件中使用一个文件的方法

swift - Xcode 8 Shell 脚本调用错误

ios - swift - PerformSegue 无法在 RxSwift Observable 订阅中工作

ios - API 网关 : Empty request body?

iphone - 对象的潜在泄漏-Xcode-iOS5

ios - Quickblox 能否在 iOS 上提供基于 Javascript 的视频聊天?

ruby-on-rails - 一个凌乱的 View 层,我应该离开 MVC 吗?

iphone - 无法在用户不可交互的 UIWebView 中激活链接

swift - 检测节点的最后位置