iOS 按钮点击区域修改 button部分区域可以点击 修改点击区域

 

比如

一个按钮,只让中间点击区域点击有效,其他地方点击无效,重写UIButton的两个方法

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event

iOS 按钮点击区域修改 button部分区域可以点击 修改点击区域

 

 

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    if (self.hidden ||
        self.alpha < 0.01 ||
        self.userInteractionEnabled  == NO) {
        return nil;
    }
    
    if ([self pointInside:point withEvent:event]) {
        
        __block UIView * hit = nil;
        
        [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            //把点击的点转为子视图的坐标点
            CGPoint subConv = [self convertPoint:point toView:obj];
            
            hit = [self hitTest:subConv withEvent:event];
            
            if (hit) {
                 *stop = YES;
            }
           
        }];
        
        return hit != nil ? hit : self ;
        
    } else {
        return nil;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat clickX = point.x;
    CGFloat clickY = point.y;
    
    CGFloat centerX = self.frame.size.width / 2.0;
    CGFloat centerY = self.frame.size.height / 2.0;
    
    //直角三角形求斜角长度
    CGFloat distance = sqrt((centerX - clickX) * (centerX - clickX) + (centerY - clickY) * (centerY - clickY));
    
    if (distance < self.frame.size.width / 2) {
        return YES;
    } else {
        return NO;
    }
    
}

 

iOS 按钮点击区域修改 button部分区域可以点击 修改点击区域

上一篇:Android - 采用 SharedPreferences 存储数据


下一篇:原生js中,call(),apply(),bind()三种方法的区别