IOS開發之——事件處理-hiTest

文章搬運來源:blog.csdn.net/Calvin_zhou…面試

做者:PGzxcmarkdown

對iOS開發感興趣,能夠看一下做者的iOS交流羣:812157648,你們能夠在裏面吹水、交流相關方面的知識,羣裏還有我整理的有關於面試的一些資料,歡迎你們加羣,你們一塊兒開車ide

一 概述

  • hiTest方法的介紹
  • hiTest底層實現原理
  • hiTest練習

二 hiTest方法的介紹

2.1 hiTest方法介紹

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

複製代碼

2.2 什麼時候調用

當事件傳遞給一個控件的時候就會調用oop

2.3 調用過程

  • 看窗口是否能接收,若是不能return nil;本身不能接收事件,也不能處理事件,並且也不能把事件傳遞給子控件
  • 判斷點在不在窗口上,若是點在窗口上,意味着窗口知足合適的view

2.4 做用

尋找最合適的view佈局

三 hiTest底層實現原理

3.1 座標系轉換關係

  • 判斷點在不在方法調用者的座標系上(point:是方法調用者的座標系上的點)

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 要求

  • 界面上有一個Button,Button上方有一個GreenView佈局
  • 點擊Button時,Button響應請求
  • 點擊Button上方的GreenView時,Button響應請求
  • 點擊GreenView上的其餘區域時,GreenView響應請求

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
複製代碼
相關文章
相關標籤/搜索