[英]iOS Xcode (swift) - how to execute code after unwind segue
我從場景1到場景2執行一個segue。然后我從場景2返回到場景1.我如何不僅將場景2中的數據傳遞到場景1,還在場景1中檢測到我從場景2返回並執行代碼在場景1?
在Android中,我使用startActivity和onActivityResult執行此操作。
像其他答案一樣介紹Bool
狀態是非常糟糕的 ,必須盡可能避免,因為它會大大增加應用程序的復雜性。
在許多其他模式中,解決此類問題最簡單的方法是將delegate
對象傳遞給Controller2
。
protocol Controller2Delegate {
func controller2DidReturn()
}
class Controller1: Controller2Delegate {
func controller2DidReturn() {
// your code.
}
func prepareForSegue(...) {
// get controller2 instance
controller2.delegate = self
}
}
class Controller2 {
var delegate: Controller2Delegate!
func done() {
// dismiss viewcontroller
delegate.controller2DidReturn()
}
}
國家是邪惡的 ,是軟件漏洞的最大單一來源。
你可以這樣做:
class SourceViewController: UIViewController {
var didReturnFromDestinationViewController = false
@IBAction func returnToSourceViewController(segue: UIStoryboardSegue) {
didReturnFromDestinationViewController = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if didReturnFromDestinationViewController == true {
// reset the value
didReturnFromDestinationViewController = false
// do whatever you want
}
}
}
我遇到的問題是我試圖在展開segue完成后顯示警告對話框。 所以我的View Controller 2對View Controller 1進行了展開。我發現調用unwind segue方法后運行的代碼在View Controller 2被解除之前運行,所以當我試圖顯示一個警告對話框時,它會視線控制器2被解雇后立即消失。
如果其他解決方案不適合您,請按我的方式行事。 我向我的類添加了一個viewWillAppear覆蓋並解除了那里的父控制器,然后在我的警報對話框中添加了代碼。 為了確保viewWillAppear在第一次出現View Controller 1時沒有顯示警告對話框,我設置了一個if語句,檢查我在類中聲明的變量名稱,並設置為等於“”。 然后在View Controller 2中,我將變量中的一些文本傳遞回View Controller 1,因此當if語句運行時,它會測試不等於“”的變量,當它發現它不是時,代碼就會運行。 在我的例子中,變量被命名為“firstname”。
override func viewWillAppear(_ animated: Bool) {
if firstname != "" {
self.parent?.dismiss(animated: true, completion: nil)
//CustomViewController?.dismiss(animated: true, completion: nil)
let alertController = UIAlertController(title: "Hello", message: "This is a test", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.