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


背景:自定义一个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);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值