1. 程式人生 > >使用通知機制,在dismissViewControllerAnimated後,completion傳值給上一個父檢視方法

使用通知機制,在dismissViewControllerAnimated後,completion傳值給上一個父檢視方法

檢視firstView和secendView,點選firstView上面的按鈕presentviewcontroller出secendView;secendView上有個按鈕,點選按鈕dismissViewControllerAnimated,並將某個值傳給firstView,或不直接在firstView裡面的viewWillAppear裡面呼叫方法,而是直接通過在dismissViewControllerAnimated completion裡面編輯程式碼塊呼叫firstView裡面的任何方法,該怎麼做?

這個問題其實並不複雜,如果你知道如何使用NSNotificationCenter實現起來還是非常簡單的。



先說一下,secendView在dismissViewControllerAnimated後,如何在進入firstView後,自動呼叫firstView裡面的任何方法
第一步:在secendView裡面,點選按鈕時呼叫一個方法,該方法為:
-(void)secendAction{
[self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self];
    }];

}
上面程式碼是將secendView dismissViewControllerAnimated掉,然後自動註冊一個名為do的通知

註冊了這個名為的通知,你就可以在任何.m檔案裡面通過以下程式碼呼叫到了:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
           selector:@selector(handleColorChange:)
               name:@"do"
             object:nil];
上面的程式碼的意思就是,先找到已經註冊過的名為do的通知,然後再自動呼叫handleColorChange去處理,
所以:
第二步:在firstView裡面的viewWillAppear方法裡面寫入以下程式碼:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
           selector:@selector(handleColorChange:)
               name:@"do"
             object:nil];
handleColorChange方法為:
-(void)handleColorChange:(id)sender{
[self firstView裡面方法]

看明白了吧?在secendView裡面我們不直接呼叫firstView裡面的方法,而是通過通知來讓firstView自動呼叫自己裡面的某個方法。
通過通知可以讓不同.m檔案之間進行方法和引數的傳遞

ok就下來說一下如何在dismissViewControllerAnimated後將secendView裡面的值傳遞給firstView
第一步:在secendView裡面,點選按鈕時呼叫一個方法,該方法為:
-(void)secendAction{
[self dismissViewControllerAnimated:YES completion:^{
        [tools showToast:@"圖片資訊提交成功" withTime:1500 withPosition:iToastGravityCenter];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self userInfo:dictionary];
    }]; 

}
userInfo:dictionary裡面的dictionary就是你要傳遞的字典物件的值
第二步:在firstView裡面的viewWillAppear方法裡面寫入以下程式碼:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
           selector:@selector(handleColorChange:)
               name:@"do"
             object:nil];
handleColorChange方法為:
-(void)handleColorChange:(NSNotification*)sender{
NSLog(@"%@",sender);
[self firstView裡面方法]

-(void)handleColorChange:(NSNotification*)sender裡面的sender就是你在secendView裡面所傳遞的字典物件的值,簡單吧?!

相關推薦

no