zoukankan      html  css  js  c++  java
  • 新浪微博客户端(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来处理了。

      

  • 相关阅读:
    CSS概念
    CSS概念
    javascript 操作符小结
    jquery插件-自由拖拽
    MySQL随手记
    intellij 引入本地库并war打包
    Spring学习笔记3——消息队列(rabbitmq), 发送邮件
    RabbitMQ在mac上的安装
    Spring学习笔记2——表单数据验证、文件上传
    Spring学习笔记1——IOC: 尽量使用注解以及java代码
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/6180976.html
Copyright © 2011-2022 走看看