標籤:self res test 判斷 改變自己 inter cto 使用 跳轉
說明:代理傳值一般在反向傳值中使用。
本貼的例子是:有A和B兩個介面,要實現的效果就是先讓A跳轉到B,然後B中有個顏色的參數,當B跳轉到A時,把這個顏色的參數傳遞給A,在A中利用這個顏色改變自己介面的顏色。
第1步:在寄件者(介面B)中,制定協議(在.h標頭檔中聲明)
// 協議名一般以本類的類名開頭+Delegate (包含首碼)
@protocol ConfigViewControllerDelegate
// 聲明協議方法,一般以類名開頭(不需要首碼)
- (void)changeBgColor:(UIColor *)color;
第2步:在寄件者(介面B)中的.h檔案中代理協議。
@interface ConfigViewController : UIViewController
// id即表示誰都可以設定成為我的代理
@property (nonatomic,weak) id delegate;
// ARC使用weak,MRC使用assign
@end
第3步:在寄件者(介面B)中的方法中通知代理(最重要的步驟)
//這一步一般是在B跳轉到A的方法中實現的,我是在B中建立了一個Button,讓這個通知代理在Button中跳轉方法中實現。
if ([self.delegate respondsToSelector:@selector(changeBgColor:)]) {
// 加入if語句就是先判斷在介面A中是否有changeBgColor這個方法,當有這個方法的時候,才進行代理傳值。
//一般會先執行個體化出一個color的對象,在進行代理傳值的時候,是帶著這個color一起傳遞過去的。
[self.delegate changeBgColor:color];
//這裡的self是介面B,self.delegate就是介面A了(在第4步和第5步的設定中設定了)
}
第4步:在接收者(介面A)中遵守協議。
@interface ViewController ()
第5步:在接收者(介面A)中設定自己成為代理。
ConfigViewController *testVC = [[ConfigViewController alloc] init];
testVC.delegate = self;
第6步:在接受者(介面A)中實現協議中的方法。
- (void)changeBgColor:(UIColor *)color{
self.view.backgroundColor = color;
}
iOS 代理傳值