[英]Add Observer and Selector in Swift 3
我真的很难为观察者理解新的语法。
您能帮我翻译成Swift 3吗?
nc.addObserver(self, selector: #selector(MapViewController.locationUpdated(_:)), name: LocationNotification.kLocationUpdated, object: nil)
nc.addObserver(self, selector: #selector(MapViewController.locationAuthorizationStatusChanged(_:)), name: LocationNotification.kAuthorizationStatusChanged, object: nil)
nc.addObserver(self, selector: #selector(MapViewController.locationManagerDidFailWithError(_:)), name: LocationNotification.kLocationManagerDidFailWithError, object: nil)
非常感谢!
您的代码的语法对于Swift 3是有效的。通过这种语法,我假设您的LocationNotification
对象看起来像这样:
struct LocationNotification {
static let kLocationUpdated = Notification.Name(rawValue: "LocationUpdated")
static let kAuthorizationStatusChanged = Notification.Name(rawValue: "AuthorizationStatusChanged")
static let kLocationManagerDidFailWithError = Notification.Name(rawValue: "LocationManagerDidFailWithError")
}
请记住,将接受通知的方法设为公开(如果在其他控制器上)。
而且您还应该添加处理器标记objc
以便Objective-C方法可以调用它。
分配观察者:
nc.addObserver(
self,
selector: #selector(received(notification:)),
name: LocationNotification.kLocationUpdated, object: nil
)
处理通知:
@objc public func locationUpdated(notification:Notification) {
//Do something
}
希望这可以帮助! :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.