iOS 設定代理過程,ios代理過程
iOS設定代理的過程 (以類比 button 作用為例)
1.寫協議
建立一個名為 MyButton 的檔案,繼承於 UIView,在該檔案裡 聲明協議 myDelegate
2.寫協議方法
為聲明的協議添加方法
3.定義一個遵守協議的屬性
前三步代碼如下:
1 #import <UIKit/UIKit.h> 2 @class MyButton; 3 //第一步:寫協議 4 @protocol myDelegate <NSObject> 5 //第二步:寫協議方法 (參數要在上面聲明:@class MyButton;) 6 - (void)changeColor:(MyButton *) myButton; 7 @end 8 9 @interface MyButton : UIView10 //第三步:寫一個myDelegate屬性11 @property (nonatomic , assign)id<myDelegate> delegate;12 13 @end
4.寫一個調用協議的方法
寫touchesBegan 方法
5.調用協議方法
4,5步代碼:
1 //第四步 寫touchesBegan 方法2 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{3 //第五步調用協議的方法4 [_delegate changeColor:self];5 }
6.遵守協議
讓要實現協議的類遵守協議
1 //第六步 遵循協議 2 @interface RootViewController : UIViewController <myDelegate>
7.設定代理
self.rootView.myButton.delegate = self;
8.實現協議方法
1 //第八步 實現協議中的方法2 - (void)changeColor:(MyButton *)myButton{3 myButton.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];4 }