2017-01-29 3 views
1

Ich habe wirklich Mühe, die neue Syntax für Beobachter zu verstehen.Hinzufügen von Observer und Selector in Swift 3

Können Sie mir helfen, dieses 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) 

Vielen Dank an Swift zu übersetzen!

Antwort

1

Denken Sie daran, die Methode, um die Benachrichtigungen Öffentlichkeit zu akzeptieren (wenn seine auf ein anderer Controller).

Und Sie sollten auch das Prozessor-Tag objc hinzufügen, so objektive-c Methoden können es nennen.

zuordnen Beobachter:

nc.addObserver(
    self, 
    selector: #selector(received(notification:)), 
    name: LocationNotification.kLocationUpdated, object: nil 
) 

Handle Benachrichtigungen:

@objc public func locationUpdated(notification:Notification) { 
    //Do something 
} 

hoffe, das hilft! :-)

1

Die Syntax des Codes für Swift 3. Mit dieser Syntax gültig ist, gehe ich davon aus Ihrem LocationNotification Objekt etwas wie folgt aussieht:

struct LocationNotification { 
    static let kLocationUpdated = Notification.Name(rawValue: "LocationUpdated") 
    static let kAuthorizationStatusChanged = Notification.Name(rawValue: "AuthorizationStatusChanged") 
    static let kLocationManagerDidFailWithError = Notification.Name(rawValue: "LocationManagerDidFailWithError") 
} 
Verwandte Themen