美文网首页
增大或缩小按钮的点击触发区域

增大或缩小按钮的点击触发区域

作者: _RG | 来源:发表于2020-01-03 15:29 被阅读0次

    当遇到增大或缩小按钮的点击触发区域,或者不规则形状按钮的事件触发

    自定义按钮,重写- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event的方法, 在pointInside方法里面设置触发的范围即可

    //左右增加的区域
    @property(nonatomic,assign) CGFloat leftRightLength;
    //上下增加的区域
    @property(nonatomic,assign) CGFloat topBottomLenght;
    
    - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
        
        CGRect originBounds = self.bounds;
        CGFloat newX = originBounds.origin.x - self.leftRightLength;
        CGFloat newY = originBounds.origin.y - self.topBottomLenght;
        CGFloat newW = originBounds.size.width + self.leftRightLength*2;
        CGFloat newH = originBounds.size.height + self.leftRightLength*2;
        CGRect currentBounds = CGRectMake(newX, newY, newW, newH);
        NSLog(@"currentBounds = %@",NSStringFromCGRect(currentBounds));
        NSLog(@"point = %@",NSStringFromCGPoint(point));
        return CGRectContainsPoint(currentBounds, point);
    }
    

    一个事件的传递, 首先会调用页面的- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event方法, 在hitTest方法里面判断是否有子控件可以响应,如果没有就会通过- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event判断自己能否响应

    hitTest:withEvent:方法的伪代码
    //返回最适合处理事件的视图,最好在父视图中指定子视图的响应
    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        if (!self.userInteractionEnabled || !self.hidden || self.alpha <= 0.01) {
            return nil;
        }
        
        if ([self pointInside:point withEvent:event]) {
            
            for (UIView *subView in [self.subviews reverseObjectEnumerator]) {
                CGPoint subPoint = [subView convertPoint:point fromView:self];
                
                UIView *bestView = [subView hitTest:subPoint withEvent:event];
                if (bestView) {
                    return bestView;
                }
            }
            return self;
        }
    
        return nil;
    }
    

    相关文章

      网友评论

          本文标题:增大或缩小按钮的点击触发区域

          本文链接:https://www.haomeiwen.com/subject/tlwzoctx.html