戴珍珠耳钉的大叔 發表於 2021-1-27 14:36:00

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

<p>文章搬运来源:https://blog.csdn.net/Calvin_zhou/article/details/111149836?spm=1001.2014.3001.5501<br>
作者:PGzxc<br>
<strong>对iOS开发感兴趣,可以看一下作者的iOS交流群:812157648,大家可以在里面吹水、交流相关方面的知识,群里还有我整理的有关于面试的一些资料,欢迎大家加群,大家一起开车</strong></p>
<h2 id="一-概述">一 概述</h2>
<ul>
<li>hiTest方法的介绍</li>
<li>hiTest底层实现原理</li>
<li>hiTest练习</li>
</ul>
<h2 id="二-hitest方法的介绍">二 hiTest方法的介绍</h2>
<h3 id="21-hitest方法介绍">2.1 hiTest方法介绍</h3>
<pre><code>- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event

</code></pre>
<h3 id="22-何时调用">2.2 何时调用</h3>
<p>当事件传递给一个控件的时候就会调用</p>
<h3 id="23-调用过程">2.3 调用过程</h3>
<ul>
<li>看窗口是否能接收,如果不能return nil;自己不能接收事件,也不能处理事件,而且也不能把事件传递给子控件</li>
<li>判断点在不在窗口上,如果点在窗口上,意味着窗口满足合适的view</li>
</ul>
<h3 id="24-作用">2.4 作用</h3>
<p>寻找最合适的view</p>
<h2 id="三-hitest底层实现原理">三 hiTest底层实现原理</h2>
<h3 id="31-坐标系转换关系">3.1 坐标系转换关系</h3>
<ul>
<li>判断点在不在方法调用者的坐标系上(point:是方法调用者的坐标系上的点)</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/25330009-797af033b06ac343.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<h3 id="32-底层实现原理">3.2 底层实现原理</h3>
<pre><code>- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (self.userInteractionEnabled==NO||self.hidden==YES||self.alpha&lt;=0.01) {
      return nil;
    }
    if (!) {
      return nil;
    }
    int count=self.subviews.count;
    for (int i=count-1; i&gt;=0; i--) {
      UIView *childView=self.subviews;
      //转换坐标系
      CGPoint childPoint=;
       UIView *fitView= ;
      if (fitView) {
            return fitView;
      }
    }
    returnself;
}

</code></pre>
<h2 id="四-hitest练习">四 hiTest练习</h2>
<h3 id="41-界面">4.1 界面</h3>
<p><img src="https://upload-images.jianshu.io/upload_images/25330009-42ca8532b12b4c55.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<h3 id="42-要求">4.2 要求</h3>
<ul>
<li>界面上有一个Button,Button上方有一个GreenView布局</li>
<li>点击Button时,Button响应请求</li>
<li>点击Button上方的GreenView时,Button响应请求</li>
<li>点击GreenView上的其他区域时,GreenView响应请求</li>
</ul>
<h3 id="43-代码逻辑">4.3 代码逻辑</h3>
<h4 id="greenviewh">GreenView.h</h4>
<pre><code>@interface GreenView : UIView
@property (nonatomic,weak) IBOutlet UIButton *button;
@end

</code></pre>
<h4 id="greenviewm">GreenView.m</h4>
<pre><code>#import "GreenView.h"

@implementation GreenView

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

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

    //把自己的点转换为按钮坐标系上的点
    CGPoint buttonPoint=;
    if () {
      return nil;
    }
    return;
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGPoint buttonPoint=;
    if () {
      return NO;
    }
    return;
}
@end
</code></pre><br><br>
来源:https://www.cnblogs.com/fadaijun/p/14334899.html
頁: [1]
查看完整版本: IOS开发之——事件处理-hiTest