iOS多层级View事件处理

开发过程中可能会遇到这种情形,由于业务逻辑可能相对复杂,我们封装了很多不同的View,可能会遇到多层嵌套的情况,那么事件View的事件应该如何处理呢?因为事件交给View来处理在逻辑上是不合理的,一般都会交给控制器来处理,那么应该如何实现呢?直接进入正题----

通过响应者链来实现View的事件传递

核心思路:UIView继承自UIResponder, 我们可以通过实现一个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

两个自定义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:@"一个按钮" 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":@"按钮点击后传递的参数"}];
}
@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中实现分类方法
层级关系

方法已经写得十分详细了,如有其它更好地方法,欢迎交流!

你可能感兴趣的:(iOS多层级View事件处理)