簡體   English   中英

在關閉所顯示的ViewController時獲得通知

[英]Get notified when a presented ViewController is dismissed

我正在使用presentViewController呈現一個ViewController。 當顯示的ViewController自行關閉時,我需要執行一些操作。 目前,我為呈現的ViewController定義了一個協議,並在呈現的ViewController中的dismissViewControllerAnimated的完成塊中調用了相應的方法。 有沒有更直接的方法?

我相信使用委托是最好的方法。 但仍然可以在類NSNotificationCenter的幫助下使用其他替代方法。

您可以為您的VC(當前VC的父視圖VC)注冊/添加觀察者通知。

[[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(myVCDismissNotification:) 
        name:@"MyVCDismissNotification"
        object:nil];

在同一個類中定義方法(每當通知發布時,它將得到調用)

-(void) myVCDismissNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"MyVCDismissNotification"])
        NSLog (@"Successfully received the Dismiss notification!");
         //You can use it in your way.
}

請記住在父VC中使用此功能。

 [[NSNotificationCenter defaultCenter] removeObserver:self];

在當前的VC中,關閉VC時,請調用以下方法

 [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"MyVCDismissNotification" 
        object:self];

有關通知的更多說明,請參閱Apple Docs。 編碼愉快。

您可以使用委托並讓委托在調用dismissViewController之前dismissViewController執行適當的方法,或者使用unwind segue代替dismissViewController ,也可以按照當前的方式進行操作。 如果希望在顯示的視圖控制器關閉立即運行這些操作,這聽起來好像是正確的做法。 這就是為什么完成塊存在於dismissViewController 使用委派意味着操作將在顯示的視圖控制器被解雇之前立即運行。

暫無
暫無

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

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