您的位置:首页 > 移动开发 > IOS开发

IOS代理模式(监听器模式)

2016-01-12 15:08 387 查看
背景:自定义一个View,在View中进行了一系列的操作后,需要将结果返回给ViewController中,如何实现呢?需要用到delegate模式。

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: