• 新浪微博客户端(59)-hitTest withEvent方法的使用说明


    iOS中的触摸事件总是由最顶层的View首先得到的,当这个View得到该触摸事件的时候可以选择通过

    - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    
        return YES;
    
    }

    方法来决定是否由当前控件来消费掉触摸事件,YES代表由当前控件消费,事件则不再向下传递;No代表事件继续向下传递。与android里面的onTouchEvent返回布尔值类似。

    当我们决定由当前控件来消费掉此事件时,还可以进一步决定由当前控件的哪一个子控件(包括自身)来消费掉此触摸事件,为此苹果提供了下列方法

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
        return self.redView;
    
    }

    通过指定返回的View来告诉操作系统,具体由哪一个控件来消费掉触摸事件。

    示例代码:

    在Xcode中创建两个自定义View,GreenView和RedView

    GreenView.m

    #import "GreenView.h"
    #import "RedView.h"
    
    
    @interface GreenView()
    
    @property (nonatomic,weak) UIView *redView;
    
    @end
    
    @implementation GreenView
    
    
    - (void)awakeFromNib {
    
        self.backgroundColor = [UIColor greenColor];
    
        
        RedView *redView = [[RedView alloc] init];
        redView.frame = CGRectMake(100, 100, 100, 100);
        [self addSubview:redView];
        self.redView = redView;
        
    }
    
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
        NSLog(@"GreenView 被点击");
    
    }
    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
        return self.redView;
    
    }
    
    
    @end

    RedView.m

    #import "RedView.h"
    
    @implementation RedView
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            
            self.backgroundColor = [UIColor redColor];
            
        }
        return self;
    }
    
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
        NSLog(@"RedView 被点击...");
    
    
    }
    
    
    @end

    为简化操作,将默认的storyboard中创建的View,修改为GreenView:

    项目目录:

    我们在GreenView中添加了如下代码,保证当GreenView收到触摸事件时,转交给RedView来处理:

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
        return self.redView;
    
    }

    运行:

    此时,我们可以点击绿色的任意区域,发现系统打印的Log已经变成:

    说明我们已经成功的将GreenView的触摸事件交给RedView来处理了。

      

  • 相关阅读:
    《上帝掷骰子吗》总结
    每日知识卡片 20202022年
    记一次雨中小场景
    《自控力》总结
    解决vmware 宿主机无法访问centos虚拟机问题
    解决vmware 宿主机无法访问centos虚拟机问题
    dynamic datasource
    CentOS 7 Docker镜像加速器配置
    update测试用例(mysql)
    测试人员参加项目POC的核心价值
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/6180976.html
Copyright © 2020-2023  润新知