首页 > 移动平台 > 详细

iOS 设置代理过程

时间:2015-10-24 20:18:05      阅读:257      评论:0      收藏:0      [点我收藏+]

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 }

 

iOS 设置代理过程

原文:http://www.cnblogs.com/Ager/p/4907437.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!