【OC梳理】事件传递响应链-实战篇(伪)

2018-09-13  本文已影响38人  忠橙_g

接上篇,【OC梳理】事件传递响应链-原理篇
对于事件传递响应链,最常见的处理就是处理不规则区域的点击事件(例如以前常见的中间按钮凸起的tabbar),接下来模拟一下这种需求:

中间凸起的Tabbar

用一个自定义的View模拟tabbar的样式:

这个图形可以简单地拆分成为 矩形+圆 的合成,我们使用UIBezierPath可以很容易地绘制出来:

- (UIBezierPath *)tabbarPointsWithStartPoint:(CGPoint)startPoint
                              rectangleWidth:(CGFloat)rectangleWidth
                             rectangleHeight:(CGFloat)rectangleHeight
                                circleRadius:(CGFloat)circleRadius{
    UIBezierPath *linePath = [UIBezierPath bezierPathWithRect:CGRectMake(startPoint.x, startPoint.y, rectangleWidth, rectangleHeight)];
    [linePath addArcWithCenter:CGPointMake(startPoint.x + rectangleWidth/2.f, startPoint.y + rectangleHeight - circleRadius) radius:circleRadius startAngle:0 endAngle:2*M_PI clockwise:YES];
    
    return linePath;
}

然后自定义一个View,方便测试:

@interface TestView : UIView

/// 设置路径
@property ( nonatomic, assign ) CGPathRef path;

@end

@implementation TestView{
    CAShapeLayer *shapeLayer;
}

- (void)setPath:(CGPathRef)path{
    _path = path;
    shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = _path;
    shapeLayer.fillColor = [UIColor whiteColor].CGColor;
    shapeLayer.fillRule = kCAFillRuleNonZero;
    self.layer.mask = shapeLayer;
}

- (void)dealloc{
    CFRelease(_path);
}

@end

添加到ViewController中:

TestView *testView = [[TestView alloc]initWithFrame:CGRectMake(20, 40, 250, 250)];
testView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:testView];
    
testView.path = [self tabbarPointsWithStartPoint:[testView convertPoint:CGPointMake(20, 290 - 49) fromView:self.view] rectangleWidth:250 rectangleHeight:49 circleRadius:30].CGPath;

很好 界面效果出来了,接下来给testView添加点击事件:

  // ...
  UITapGestureRecognizer *suptap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewTarget:)];
  [testView addGestureRecognizer:suptap];
//...
- (void)viewTarget:(UITapGestureRecognizer *)tap{
    NSLog(@"点击了testView");
}

然后加上上一篇的事件处理:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    if (self.userInteractionEnabled
        && !self.hidden
        && [self pointInside:point withEvent:event]) {
        // 使用reverseObjectEnumerator进行倒序遍历
        for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
            CGPoint convertedPoint = [subview convertPoint:point fromView:self];
            UIView *responseView = [subview hitTest:convertedPoint withEvent:event];
            if (responseView) {
                return responseView;
            }
        }
        return self;
    }
    return nil;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    if (self.userInteractionEnabled
        && !self.hidden
        && CGRectContainsPoint(self.bounds, point)) {
        return YES;
    }
    for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
        CGPoint convertedPoint = [subview convertPoint:point fromView:self];
        BOOL inside = [subview pointInside:convertedPoint withEvent:event];
        if (inside) {
            return YES;
        }
    }
    return NO;
}

现在点击红框区域就能输出点击了testView了:

现在要如何让testView只在灰色区域响应点击事件呢?


对于判断点与多边形的关系,经典的一个算法是射线检测算法
OC中提供了一个判断path与点是否相交的方法:

/* Return true if `point' is contained in `path'; false otherwise. A point
   is contained in a path if it is inside the painted region when the path
   is filled; if `eoFill' is true, then the even-odd fill rule is used to
   evaluate the painted region of the path, otherwise, the winding-number
   fill rule is used. If `m' is non-NULL, then the point is transformed by
   `m' before determining whether the path contains it. */

CG_EXTERN bool CGPathContainsPoint(CGPathRef cg_nullable path,
    const CGAffineTransform * __nullable m, CGPoint point, bool eoFill)
    CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);

翻译一下参数:

/**
判断点是否在path内

 @param path 路径path
 @param m 变换矩阵,可以不传
 @param point 点
 @param eoFill 填充规则,如果为true使用奇偶校验(对应CAShapeLayer中的kCAFillRuleEvenOdd),如果为false使用非0校验(对应kCAFillRuleNonZero)
 @return 如果点在path中,则返回true;否则为false。
 */
CG_EXTERN bool CGPathContainsPoint(CGPathRef cg_nullable path,
    const CGAffineTransform * __nullable m, CGPoint point, bool eoFill)
    CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);

关于eoFill的两个值,这里说一下我的理解:

kCAFillRuleNonZero:
使用非0校验规则。对路径划分出来的区域,每个区域取任意点做任意方向的射线。如果路径从左往右(基于射线方向)穿过该射线,则+1;从右往左穿过,则-1。如果计算总和为0,则判断该点在路径外,该区域不填充;反之,计算总和为0,则判断该点在路径内,该区域填充。
kCAFillRuleEvenOdd:
使用奇偶校验规则。对路径划分出来的区域,每个区域取任意点做任意方向的射线。如果有任意路径穿过该射线,则+1。如果计算总和为偶数,则判断该点在路径外,该区域不填充;反之,如果计算总和为奇数,则判断该点在路径内,该区域填充。

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event方法中稍作修改:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    if (self.userInteractionEnabled
        && !self.hidden
        && CGRectContainsPoint(self.bounds, point)) {
        /**
            可以使用下面的代码让区域上移10:
            CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 10);
            CGPathContainsPoint(shapeLayer.path, &transform, point, NO)     
        **/
        // 判断点是否在范围内
        if (CGPathContainsPoint(shapeLayer.path, nil, point, NO)) {// YES对应kCAFillRuleEvenOdd ,NO对应 kCAFillRuleNonZero
            NSLog(@"点击了shapeLayer");
        }
        return YES;
    }
    for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
        CGPoint convertedPoint = [subview convertPoint:point fromView:self];
        BOOL inside = [subview pointInside:convertedPoint withEvent:event];
        if (inside) {
            return YES;
        }
    }
    return NO;
}

现在点击红框区域还是输出点击了testView,点击灰色区域,则会输出:
... 点击了shapeLayer
... 点击了shapeLayer
... 点击了subview

为什么会输出两次点击了shapeLayer?

原因是在响应过程中同一个testView的- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event会被调用两次,一次是查找响应对象的入栈操作,一次是响应方法时的出栈操作。

现在将pointInside:withEvent:方法改为在灰色区域才返回YES,就能只响应灰色区域的点击事件啦:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    if (self.userInteractionEnabled
        && !self.hidden
        && CGRectContainsPoint(self.bounds, point)) {
        // 判断点是否在范围内
        if (CGPathContainsPoint(shapeLayer.path, nil, point, NO)) {// YES对应kCAFillRuleEvenOdd ,NO对应 kCAFillRuleNonZero
            return YES;
        }
    }
    for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
        CGPoint convertedPoint = [subview convertPoint:point fromView:self];
        BOOL inside = [subview pointInside:convertedPoint withEvent:event];
        if (inside) {
            return YES;
        }
    }
    return NO;
}

画一个五角星的点击区域?


是不是很简单呢?就这样啦~


上一篇下一篇

猜你喜欢

热点阅读