IOS开发之——事件处理-hiTest

2021-01-27  本文已影响0人  iOS发呆君

文章搬运来源:https://blog.csdn.net/Calvin_zhou/article/details/111149836?spm=1001.2014.3001.5501
作者:PGzxc
对iOS开发感兴趣,可以看一下作者的iOS交流群:812157648,大家可以在里面吹水、交流相关方面的知识,群里还有我整理的有关于面试的一些资料,欢迎大家加群,大家一起开车

一 概述

二 hiTest方法的介绍

2.1 hiTest方法介绍

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

2.2 何时调用

当事件传递给一个控件的时候就会调用

2.3 调用过程

2.4 作用

寻找最合适的view

三 hiTest底层实现原理

3.1 坐标系转换关系

image

3.2 底层实现原理

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (self.userInteractionEnabled==NO||self.hidden==YES||self.alpha<=0.01) {
        return nil;
    }
    if (![self pointInside:point withEvent:event]) {
        return nil;
    }
    int count=self.subviews.count;
    for (int i=count-1; i>=0; i--) {
        UIView *childView=self.subviews[i];
        //转换坐标系
        CGPoint childPoint=[self convertPoint:point toView:childView];
       UIView *fitView= [childView hitTest:childPoint withEvent:event];
        if (fitView) {
            return fitView;
        }
    }
    return  self;
}

四 hiTest练习

4.1 界面

image

4.2 要求

4.3 代码逻辑

GreenView.h

@interface GreenView : UIView
@property (nonatomic,weak) IBOutlet UIButton *button;
@end

GreenView.m

#import "GreenView.h"

@implementation GreenView

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%s",__func__);
}

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

    //把自己的点转换为按钮坐标系上的点
    CGPoint buttonPoint=[self convertPoint:point toView:_button];
    if ([_button pointInside:buttonPoint withEvent:event]) {
        return nil;
    }
    return  [super hitTest:point withEvent:event];
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGPoint buttonPoint=[self convertPoint:point toView:_button];
    if ([_button pointInside:buttonPoint withEvent:event]) {
        return NO;
    }
    return  [super pointInside:point withEvent:event];
}
@end
上一篇 下一篇

猜你喜欢

热点阅读