IOS代理模式(监听器模式)
2016-01-12 15:08
387 查看
背景:自定义一个View,在View中进行了一系列的操作后,需要将结果返回给ViewController中,如何实现呢?需要用到delegate模式。
1. 首先定义一个代理协议类,如代码:
2. 创建自定义View ,由于需要将自定义View中的数据传递到ViewController中,所以自定义View中一定要包含一个代理类。
如:MyCustomView.h
3. 自定义View 的实现类如:
4. ViewController中的用法,需要在ViewController中实现这个代理协议
代码如:
1. 首先定义一个代理协议类,如代码:
@protocol MyCustomViewDelegate <NSObject> @required - (void)returnTheResult:(NSString *)result; @end
2. 创建自定义View ,由于需要将自定义View中的数据传递到ViewController中,所以自定义View中一定要包含一个代理类。
如:MyCustomView.h
#import "MyCustomViewDelegate.h" @interface MyCustomView : UIView @property(nonatomic,assign) id<MyCustomViewDelegate> delegate; @property(nonatomic,strong) UIButton *button; @property(nonatomic,strong) UITextField *textField; @end
3. 自定义View 的实现类如:
@implementation MyCustomView /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ - (instancetype)init{ self = [super init]; if (self) { self.bounds = CGRectMake(0, 0, ScreenWidth, 100); self.backgroundColor = [UIColor grayColor]; [self initButtonView]; [self initTextField]; } return self; } - (void)initTextField{ self.textField = [[UITextField alloc]init]; self.textField.frame = CGRectMake(20, 10, ScreenWidth-40, 40); self.textField.textAlignment = NSTextAlignmentLeft; self.textField.secureTextEntry = NO; self.textField.placeholder = @"输入昵称"; [self.textField setBorderStyle:UITextBorderStyleRoundedRect]; [self addSubview:self.textField]; } - (void)initButtonView{ self.button = [UIButton buttonWithType:UIButtonTypeCustom]; self.button.frame = CGRectMake(20, 50, ScreenWidth-40, 40); self.button.backgroundColor = [UIColor redColor]; [self.button setTitle:@"OK" forState:UIControlStateNormal]; [self.button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:self.button]; } - (void)clickButton{ NSLog(@"clickButton"); if (self.delegate != nil) { [self.delegate returnTheResult:self.textField.text]; } } @end
4. ViewController中的用法,需要在ViewController中实现这个代理协议
代码如:
@interface ViewController ()<MyCustomViewDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; MyCustomView *myView = [[MyCustomView alloc]init]; myView.frame = CGRectMake(0, 200, ScreenWidth, 200); myView.delegate = self; [self.view addSubview:myView]; } - (void)returnTheResult:(NSString *)result{ NSLog(@"get --result:%@",result); }
相关文章推荐
- ios视图frame与bounds的区别
- ios 轻扫手势
- ios 旋转手势
- ios 缩放手势
- [iOS]FFmpeg框架在iOS平台上的编译和使用
- ios开发下的点透处理
- IOS开发之关于cocoaPods 第三方的使用
- iOS开发插件集
- iOS--错误集锦--Your session has expired. Please log in.
- Cacti和Nagios整合
- IOS中延时执行的几种方式的比较和汇总
- iOS应用性能调优的25个建议和技巧
- iOS 开发 版本控制 svn + Versions/Cornerstone
- ios解析html
- ios获取设备信息总结
- IOS生成与读取二维码名片
- iOS 开发之 Cocoapods
- iOS 监听用户是否手动修改了设备时间
- iOS开发-动画总结
- iOS 9的 Universal Links 通用链接使用介绍