2. UIButton的事件响应

2021-08-16  本文已影响0人  LeeDev

前面介绍了响应的基础 和 手势的优先级
https://www.jianshu.com/p/1e549c0669d8

接下来我们看看 UIButton的时间是怎么过来的,还是自定义一个MyButton ,并添加到 控制器的self.view 中;

@implementation MyButton

 

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addTarget:self action:@selector(myBtnClick_UIControlEventTouchDown) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(myBtnClick_EventTouchUpInside) forControlEvents:UIControlEventTouchUpInside];

    }
    return self;
}

- (void)myBtnClick_UIControlEventTouchDown {
    
    NSLog(@"myBtnClick_UIControlEventTouchDown");
}

- (void)myBtnClick_EventTouchUpInside {
    
    NSLog(@"myBtnClick_EventTouchUpInside");
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"MyButton:%p touchesBegan",self);

    // UIControl 类不会让事件传递出去,直接 通过 [UIApplication SendAction:to:from:forEvent] 传递给 UIControlEventTouchDown 事件
    [super touchesBegan:touches withEvent:event];
    
    NSLog(@"MyButton:%p touchesBegan--2",self);

}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"MyButton:%p touchesMoved",self);

    
    [super touchesMoved:touches withEvent:event];
    
    NSLog(@"MyButton:%p touchesMoved---2",self);

}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"MyButton:%p touchesCancelled",self);

    [super touchesCancelled:touches withEvent:event];
    
    NSLog(@"MyButton:%p touchesCancelled--2",self);
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"MyButton:%p touchesEnded",self);
    // UIControl 类不会让事件传递出去,而是通过 [UIApplication SendAction:to:from:forEvent], 传递给自身的 UIControlEventTouchUpInside 事件
    [super touchesEnded:touches withEvent:event];
    
    NSLog(@"MyButton:%p touchesEnded--2",self);

 }

@end

通过 上面的demo 调试,也可以更加清楚 UIButton的 响应 和 手势是不一样的;

  1. MyButton 里面的 [super touchesBegan:touches withEvent:event]; 不会触发 父视图的 对应的方法;而是 会 通过 [UIApplication SendAction:to:from:forEvent] 传递给 UIControlEventTouchDown 事件

  2. MyButton 里面的[super touchesEnded:touches withEvent:event],不会触发 父视图的 对应的方法;而是 会 [UIApplication SendAction:to:from:forEvent], 传递给自身的 UIControlEventTouchUpInside

上一篇下一篇

猜你喜欢

热点阅读