• UIView局部点击(转)


     

     

    今天上班遇到一种情况,需要局部响应点击事件,比如在一个UIImageView中设置一个小圆圈图片,要求点击圆圈里面不响应点击,点击小圆圈外面的部分响应点击。
    可以通过重写hitTest:withEvent: 和 pointInside: withEvent:方法来做到。

    看一下hitTest:withEvent
    *touch事件发生,创建UIEvent对象

    *按照Application的view层次结构,逐层调用每个view的hitTest:withEvent:方法,并传入该event对象,view根据hitTest:withEvent:方法和来决定touch点是否包含在自己的bounds中;

    *如果view的bounds包含了touch点,该view会遍历自己的subview,并调用每个subview的pointInside:withEvent:方法来进一步决定touch事件是发生在自己本身,还是自己的subview上。

    *重复第二,三步,并筛选出最终接受touch事件的view对象


    //继承  建子类  重写上述方法

    复制代码
    @interface CustomImageView : UIImageView
    
    @property (strong, nonatomic) UIBezierPath *bezierPath;
    
    @end
    
    @implementation CustomImageView
    
    - (id)init
    
    {
    
        self = [super init];
    
        if (self) {
    
        }
    
        return self;
    
    }
    
    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
        
    
        UIView *result = [super hitTest:point withEvent:event];
    
        return [self pointInside:point withEvent:event] ? self : result;
    
    }
    
    - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
    
    {
    
        return CGPathContainsPoint(self.bezierPath.CGPath, NULL, point, YES) ? YES : NO;
    
    }
    
    @end
    复制代码

    //使用部分的代码
      //中间的图片

    复制代码
        CustomImageView *imageView = [[CustomImageView alloc] initWithFrame:CGRectMake(0,0, imageWidth02, imageHeight02)];
    
        imageView.backgroundColor = [UIColor clearColor];
        imageView.userInteractionEnabled = YES;
    
        imageView.bezierPath = [UIBezierPath bezierPathWithOvalInRect:imageView.bounds];
    
        imageView.image = [UIImage imageNamed:kCenterImg];
    
        [self.view addSubview:imageView];
    复制代码


    //这样就达到了点击局部响应事件的效果。关于userInteractionEnabled这个属性设置为NO的时候,表示这个view从事件队列移除出去。

  • 相关阅读:
    LeetCode-Letter Combinations of a Phone Number
    LeetCode-Sort Colors
    C++Memset误区
    LeetCode-Valid Palindrome
    LeetCode-Longest Consecutive Sequence
    C++豆知识索引
    C++ 哈希表
    LeetCode-Sum Root to Leaf Numbers
    LeetCode-Word LadderII
    LeetCode-Word Ladder
  • 原文地址:https://www.cnblogs.com/lingzeng/p/3870653.html
Copyright © 2020-2023  润新知