在第一个控制器的事件上以编程方式返回第一个控制器

时间:2016-06-07 21:11:05

标签: ios swift

在我的Swift项目中,ViewController#1在表格中列出了一系列目的地。用户正在开车,我们会跟踪用户使用内置CLLocation的位置。但是用户现在已经从ViewController#1导航到应用程序的其他部分,现在在ViewController#2中。我在ViewController#1中跟踪的某个事件会触发(在我的示例中;用户已到达其列表中的下一个目标)。当事件触发时,我需要应用程序立即切换回ViewController#1。当用户在ViewController#2中时,如何感知它?

1 个答案:

答案 0 :(得分:1)

NSNotificationCenter和Unwind Segue似乎是要走的路,这种功能可以重复使用,您需要做的就是在相关的视图控制器上注册给定的通知。

有些事情:

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.
    }
}

有一篇很好的展开文章here