簡體   English   中英

如何以模態方式呈現ViewController,然后在ViewController被解除后運行一個回調函數/塊,沒有Delegate?

[英]How to modally present a ViewController, and then the run a callback function / block after the ViewController has been dismissed, without Delegate?

我只知道在子視圖控制器完成動畫顯示在屏幕上之后,會調用self.presentViewController(childVc, animated: true, completion: {})中的完成塊self.presentViewController(childVc, animated: true, completion: {}) 我實際上想要運行一個代碼塊,在子視圖控制器的動畫完成動畫被解除后顯示 我怎么能這樣做,最好避免使用委托來做那件事?

編輯:我從提出的(子)視圖控制器這樣調用這個: self.presentingViewController.dismissViewControllerAnimated (true) {} ,但問題是子視圖控制器可以從任意頁面呈現,並在孩子被解雇后, parent(呈現)視圖控制器必須做不同的事情。 如果我在孩子中實現回調,我不能對調用它的不同父母做不同的事情。

例如,如果我在新聞屏幕中將登錄表單作為模式調用,則在登錄表單解除后,我想在之后顯示評論部分。 但是如果從產品屏幕以模態方式顯示登錄表單,我希望之后在購物車中顯示用戶的購物車。 如果沒有代表就不可能做到這一點,我仍然對委托解決方案感興趣。

您可以向ChildVC添加屬性以存儲回調閉包,並在呈現子視圖控制器時設置此屬性。 當子視圖控制器解散自身時,它可以調用完成處理程序:

class ChildVC: UIViewController {        
    var completionHandler : ((childVC:ChildVC) -> Void)?

    func dismiss() {
        self.dismissViewControllerAnimated(true) {
            self.completionHandler?(childVC:self)
        }
    }
}

在呈現ChildVC實例時提供完成處理程序:

let completionHandler:(ChildVC)->Void = { childVC in
    print("completed for \(childVC)")
}
childVC.completionHandler=completionHandler
self.presentViewController(childVC, animated: true, completion: nil)

使用dismissViewControllerAnimated API,它采用完成塊。

    self.dismissViewControllerAnimated(true) { 
        /* Do callback stuff here*/
    }

你可以在呈現的ViewController中創建一個回調塊,就像@property(nonatomic,copy)void (^onDimissed)();
在呈現的視圖控制器調用之后
[self dismissViewControllerAnimated:YES completion:^{ if (self.onDismissed) { self.onDismissed(); } }];
所以你可以在塊中返回任何參數
不要忘記制作這個
SomeController *ctr = [[UIViewController alloc] init]; ctr.onDimissed = ^{ //some your implementation };

如果你使用self.presentingViewController.dismissViewControllerAnimated (true) {}這個返回nil為什么意味着它不支持所有操作系統,所以只需使用下面的代碼,

self.dismissViewControllerAnimated(true, completion: {
   //Put your code
});

如果你關閉ViewController你可以調用任何函數將你的代碼放在完成處理程序中。

希望它有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM