TODO: 我想让一个按钮响应位于superview中的所有触摸事件,其中包含一个文本字段和一个按钮。
如何: 我重写了superView的方法hitTest:withEvent:,superView是一个自定义视图。
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
BOOL isContained = [self pointInside:point withEvent:event];
if (self.hidden || self.alpha <= 0.1 || self.userInteractionEnabled == NO || !isContained)return nil;
return self.button;
}
除此之外,我也这样做:
我只为forEvent设置按钮的目标动作:UITouchUpInside,设置为
没有更好的工作。按钮可以接收它外面的触摸事件,并且总是可以高亮,但有时可以在触摸点位于按钮外部时调用动作,有时则不能。
当我为Event设置target-action方法时:UITouchUpInside | | UITouchupOutside,有效。
问题:有人可以解释一下吗? 我在网站上完成了Xcode项目:https://github.com/hansonboy/TestHit
也许你可以下载并运行它,并找到原因。感谢。
评论:我使用Interface Builder来完成这些工作。 Xcode 7.3
答案 0 :(得分:0)
UIButton会跟踪一些触摸事件(tracking
== YES)但不会将它们视为一个触发事件,它们发生在控件的边界内(touchInside
== NO)。只需检查tracking
方法中的UIButton touchInside
,endTrackingWithTouch:withEvent
值即可。
意味着,命中测试机制按预期工作:UIButton处理事件但不触发TouchUpInside
控制事件的操作。并且由UIButton对象决定是否生成此事件。我发现当触摸非常靠近超视图边界时,UIButton的pointInside:withEvent:
会被调用。在您的情况下,它返回NO并且最终不会触发操作。
作为一种解决方案,我将以下一种方式定义类别或子类UIButton:
@interface Button : UIButton
@end
@implementation Button
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
if (!self.enabled || self.hidden || !self.userInteractionEnabled || self.alpha == 0) return [super pointInside:point withEvent:event];
CGPoint pnt = [self convertPoint:point toView:self.superview];
return CGRectContainsPoint(self.superview.bounds, pnt);
}
@end