在我的 Swift 项目中,ViewController #1 在表格中列出了目的地路线。用户正在开车,我们会跟踪用户在哪里使用内置的 CLLocation 东西。但是用户现在已经从 ViewController #1 导航到应用程序的其他部分,现在在 ViewController #2 中。我在 ViewController #1 中跟踪的某个事件触发(在我的示例中;用户已到达他列表中的下一个目的地)。我需要应用程序在该事件触发时立即返回到 ViewController #1。当用户在 ViewController #2 中时如何感知?
NSNotificationCenter 和 Unwind Segue 似乎是可行的方法,这样可以重用此功能,您需要做的就是在相关 View Controller 上注册给定的通知。
类似的东西:
class ViewControllerOne: UIViewController {
let CallForUnwindSegue = "com.yourIdentifier.unwindToVCOne"
//- your event happens
SomethingHappened {
NSNotificationCenter.defaultCenter().postNotification(CallForUnwindSegue, object: nil)
}
}
class ViewControllerTwo: UIViewController {
let CallForUnwindSegue = "com.yourIdentifier.unwindToVCOne"
override func viewDidLoad() {
super.viewDidLoad()
//- Subscribe for notifications
NSNotificationCenter.defaultCenter().addObserver(self, #selector(self.doSomething), name: CallForUnwindSegue)
}
//- Unsubscribe for notifications
override func deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func doSomething(notification: NSNotification) {
//Handle your event here.
}
}
有一篇很好的 unwind segue 文章 here