開發(fā)過程中可能會(huì)遇到這種情形,由于業(yè)務(wù)邏輯可能相對(duì)復(fù)雜,我們封裝了很多不同的View,可能會(huì)遇到多層嵌套的情況,那么事件View的事件應(yīng)該如何處理呢?因?yàn)槭录唤oView來處理在邏輯上是不合理的,一般都會(huì)交給控制器來處理,那么應(yīng)該如何實(shí)現(xiàn)呢?直接進(jìn)入正題----
通過響應(yīng)者鏈來實(shí)現(xiàn)View的事件傳遞
核心思路:UIView繼承自UIResponder, 我們可以通過實(shí)現(xiàn)一個(gè)UIResponder的分類來處理事件傳遞,直接上代碼:
@interface UIResponder (YMEvent)
/*
自定義事件傳遞方法
*/
- (void)routeEvent:(NSString *)eventName params:(NSDictionary *)params;
@end
@implementation UIResponder (YMEvent)
- (void)routeEvent:(NSString *)eventName params:(NSDictionary *)params {
[self.nextResponder routeEvent:eventString params:params];
}
@end
兩個(gè)自定義View:
static NSString * const YMButtonEvent = @"YMButtonEvent";
@interface YMSubView : UIView
@property (nonatomic, strong) UIButton *button;
@end
@implementation YMSubView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.button setTitle:@"一個(gè)按鈕" forState:UIControlStateNormal];
[self.button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
self.button.titleLabel.font = [UIFont systemFontOfSize:18];
[self.button setBackgroundColor:UIColor.blueColor];
[self.button addTarget:self action:@selector(event_buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.button];
self.button.frame = CGRectMake(20, 20, 180, 40);
}
return self;
}
- (void)event_buttonClick:(UIButton *)sender {
[self.nextResponder routeEvent:YMButtonEvent params:@{@"name":@"按鈕點(diǎn)擊后傳遞的參數(shù)"}];
}
@end
@interface YMView : UIView
@end
@implementation YMView
- (instancetype)init
{
self = [super init];
if (self) {
YMSubView *subView = [YMSubView new];
subView.backgroundColor = UIColor.yellowColor;
[self addSubview:subView];
subView.frame = CGRectMake(10, 10, 260, 100);
}
return self;
}
@end
ViewController中:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.whiteColor;
YMView *view = [YMView new];
[self.view addSubview:view];
view.backgroundColor = UIColor.purpleColor;
view.frame = CGRectMake(10, 120, 300, 300);
}
- (void)routeEvent:(NSString *)eventString params:(NSDictionary *)params {
if ([eventString isEqualToString:YMButtonEvent]) {
[self handleButtonClick:params];
} else {
[self.nextResponder routeEvent:eventString params:params];
}
}
- (void)handleButtonClick:(NSDictionary *)params {
NSLog(@"傳遞的信息: %@",params);
}

ViewController中實(shí)現(xiàn)分類方法

層級(jí)關(guān)系