iOS 設定代理過程,ios代理過程

來源:互聯網
上載者:User

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 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.