[轉(zhuǎn)載]使用通知機(jī)制,在dismissViewControllerAnimated后,completion傳值給上一個(gè)父視圖方法

dismissViewControllerAnimated后,completion傳值給上一個(gè)父視圖方法

視圖firstView和secendView,點(diǎn)擊firstView上面的按鈕presentviewcontroller出secendView;secendView上有個(gè)按鈕,點(diǎn)擊按鈕dismissViewControllerAnimated,并將某個(gè)值傳給firstView,或不直接在firstView里面的viewWillAppear里面調(diào)用方法,而是直接通過在dismissViewControllerAnimated completion里面編輯代碼塊調(diào)用firstView里面的任何方法,該怎么做?

這個(gè)問題其實(shí)并不復(fù)雜,如果你知道如何使用NSNotificationCenter實(shí)現(xiàn)起來還是非常簡(jiǎn)單的。

先說一下,secendView在dismissViewControllerAnimated后,如何在進(jìn)入firstView后,自動(dòng)調(diào)用firstView里面的任何方法

第一步:在secendView里面,點(diǎn)擊按鈕時(shí)調(diào)用一個(gè)方法,該方法為:

-(void)secendAction{

[self dismissViewControllerAnimated:YES completion:^{

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

}];

}

上面代碼是將secendView dismissViewControllerAnimated掉,然后自動(dòng)注冊(cè)一個(gè)名為do的通知

注冊(cè)了這個(gè)名為的通知,你就可以在任何.m文件里面通過以下代碼調(diào)用到了:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

[nc addObserver:self

selector:@selector(handleColorChange:)

name:@"do"

object:nil];

上面的代碼的意思就是,先找到已經(jīng)注冊(cè)過的名為do的通知,然后再自動(dòng)調(diào)用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里面我們不直接調(diào)用firstView里面的方法,而是通過通知來讓firstView自動(dòng)調(diào)用自己里面的某個(gè)方法。

通過通知可以讓不同.m文件之間進(jìn)行方法和參數(shù)的傳遞

ok就下來說一下如何在dismissViewControllerAnimated后將secendView里面的值傳遞給firstView

第一步:在secendView里面,點(diǎn)擊按鈕時(shí)調(diào)用一個(gè)方法,該方法為:

-(void)secendAction{

[self dismissViewControllerAnimated:YES completion:^{

[tools showToast:@"圖片信息提交成功" withTime:1500 withPosition:iToastGravityCenter];

[[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self userInfo:dictionary];

}];

}

userInfo:dictionary里面的dictionary就是你要傳遞的字典對(duì)象的值

第二步:在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里面所傳遞的字典對(duì)象的值,簡(jiǎn)單吧?!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容