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 : 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 }

 

转载于:https://www.cnblogs.com/Ager/p/4907437.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值