菜鸟教程小白 发表于 2022-12-12 16:01:45

ios - UIButton 处理触摸然后通过?


                                            <p><p>是否可以处理 UIButton 发生的触摸,然后将其传递给下一个响应者?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><h3>编辑</h3>
<p>一个有效的方法也是覆盖 <code>UIResponder</code></p> 的 <code>touchesEnded:withEvent:</code> 方法
<pre><code>- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // handle touch
    ;
}
</code></pre>
<p>来自 <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/UIResponder/touchesEnded:withEvent:" rel="noreferrer noopener nofollow">documentation</a> :</p>
<blockquote>
<p>The default implementation of this method does nothing. However immediate UIKit subclasses of <code>UIResponder</code>, particularly <code>UIView</code>, forward the message up the responder chain. <strong>To forward the message to the next responder, send the message to <code>super</code></strong> (the superclass implementation); do not send the message directly to the next responder.</p>
</blockquote>
<hr/>
<h3>原答案</h3>
<p>为了确定 View 层次结构中的哪个 <code>UIView</code> 应该接收触摸,使用方法 <code>-</code>。根据 <a href="https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/occ/instm/UIView/hitTest:withEvent:" rel="noreferrer noopener nofollow">documentation</a> :</p>
<blockquote>
<p>This method traverses the view hierarchy by calling the <code>pointInside:withEvent:</code> method of each subview to determine which subview should receive a touch event. If <code>pointInside:withEvent:</code> returns <code>YES</code>, then the subview’s hierarchy is similarly traversed until the frontmost view containing the specified point is found. If a view does not contain the point, its branch of the view hierarchy is ignored.</p>
</blockquote>
<p>因此,一种方法可能是创建一个 <code>UIButton</code> 子类并覆盖方法 <code>-pointInside:withEvent:</code></p>
<pre><code>- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if (CGRectContainsPoint(self.bounds, point) {
      // The touch is within the button&#39;s bounds
    }
    return NO;
}
</code></pre>
<p>这将使您有机会在按钮范围内处理触摸,但同时返回 <code>NO</code> 将使 HitTest 失败,从而在 View 层次结构中传递触摸。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - UIButton 处理触摸然后通过?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/19688328/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/19688328/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - UIButton 处理触摸然后通过?