[轉載]使用通知機制,在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里面所傳遞的字典對象的值,簡單吧?!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容