浅谈代理(delegate),我们在开发中,经常遇到实现某一个类的.delegate = self,然后实现它的代理方法。使用的多了就越来越感觉,代理就是类似一个方法列表这句话的意义所在,我们遵循一个类的代理,然后在方法列表里选择自己需要的的方法接口(API),也有一些是必须要实现的方法(@requiret),就像UITableView里的两个必须要实现的方法,而其他的方法都是可选的(@optional)。
1、声明一个协议(代理),使用@protocol关键字声明一个代理,例如自定义View里,我们添加一个协议,并创建方法列表,不同的方法实现不同的效果,
CustomView.h
#import <UIKit/UIKit.h>
@protocol CustomViewDelegate <NSObject>
@required(必须要实现的方法)
- (void)oneClick:(NSString *)oneStr;
- (void)twoClick:(int)twoStr;
@optional (可选的方法)
- (void)threeClick:(UIButton *)clickBtn;
@end
@interface CustomView : UIView
//代理用weak修饰,避免循环引用(weak不会引起野指针,比assign安全些)
@property (nonatomic,weak) id<CustomViewDelegate> delegate;
@end
CustomView.m
#import "CustomView.h"
@implementation CustomView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor yellowColor];
for (int i = 0; i<3; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.tag = 10+i;
btn.backgroundColor = [UIColor orangeColor];
btn.frame = CGRectMake(10, 10+(60)*i, self.bounds.size.width-20, 50);
[btn setTitle:[NSString stringWithFormat:@"第%d行",i] forState:normal];
[self addSubview:btn];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
}
}
return self;
}
- (void)btnClick:(UIButton *)sender {
if (sender.tag == 10) {
[self.delegate oneClick:@"111111"];
}else if (sender.tag == 11) {
[self.delegate twoClick:2222222];
}else {
[self.delegate threeClick:sender];
}
}
@end
至此我们就已经成功的创建了一个包含代理(方法列表)的自定义view,并且方法列表里我们都自带了一个参数,第一个方法中携带字符串类型的参数,第二个方法里携带int类型的参数,第三个方法里携带了一个UIButton的参数。其他任何需要添加该CustomView的地方,都要遵循它的代理,该CustomView携带一个拥有3个方法的列表(2个必须一个可选)。
代理传值就是这样实现的。
2、我们在ViewController里添加该CustomView,并查看它的方法列表
.h里不需要任何操作
ViewController.m
#import "ViewController.h"
#import "CustomView.h"
@interface ViewController ()<CustomViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CustomView *customView = [[CustomView alloc]initWithFrame:CGRectMake(200, 300, 100, 200)];
customView.delegate = self;
[self.view addSubview:customView];
}
- (void)oneClick:(NSString *)oneStr {
NSLog(@"%@",oneStr);
}
- (void)twoClick:(int)twoStr {
NSLog(@"%d",twoStr);
}
- (void)threeClick:(UIButton *)clickBtn {
NSLog(@"%@",clickBtn.currentTitle);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end







网友评论