·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS设置代理过程

iOS设置代理过程

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

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 : UIView
10 //第三步:写一个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 }