iOS 区域响应交互

2019-03-18  本文已影响0人  CaptainRoy
//  获取响应的视图
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
// 获取响应位置
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
#import <UIKit/UIKit.h>

@interface CustomButton : UIButton

@end
#import "CustomButton.h"

@implementation CustomButton


- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (!self.userInteractionEnabled || [self isHidden] || self.alpha <= 0.01) { // 如果是禁止交互,隐藏,透明则不用响应 返回 nil
        return nil;
    }
    
    if ([self pointInside:point withEvent:event]) {
        //遍历当前对象的子视图
        __block UIView *hit = nil;
        [self.subviews enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 坐标转换
            CGPoint vonvertPoint = [self convertPoint:point toView:obj];
            //调用子视图的hittest方法
            hit = [obj hitTest:vonvertPoint withEvent:event];
            // 如果找到了接受事件的对象,则停止遍历
            if (hit) {
                *stop = YES;
            }
        }];
        
        if (hit) {
            return hit;
        }
        else{
            return self;
        }
    }
    else{
        return nil;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGFloat x1 = point.x;
    CGFloat y1 = point.y;
    
    CGFloat x2 = self.frame.size.width / 2;
    CGFloat y2 = self.frame.size.height / 2;
    
    double dis = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    // 67.923
    if (dis <= self.frame.size.width / 2) {
        return YES;
    }
    else{
        return NO;
    }
}
CustomButton *customButton = [[CustomButton alloc] initWithFrame:CGRectMake(100, 100, 120, 120)];
    customButton.backgroundColor = [UIColor blueColor];
    [customButton addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:customButton];
上一篇 下一篇

猜你喜欢

热点阅读