当 UIButton 的框架位于其父框架之外时,UIButton(或任何其他控件)是否有可能接收触摸事件?因为当我尝试这个时,我的 UIButton 似乎无法接收任何事件.我该如何解决这个问题?
Is it possible for a UIButton (or any other control for that matter) to receive touch events when the UIButton's frame lies outside of it's parent's frame? Cause when I try this, my UIButton doesn't seem to be able to receive any events. How do I work around this?
是的.您可以覆盖 hitTest:withEvent:
方法以返回一个视图,该视图包含比该视图包含的更大的点集.请参阅 UIView 类参考.
Yes. You can override the hitTest:withEvent:
method to return a view for a larger set of points than that view contains. See the UIView Class Reference.
示例:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
CGFloat radius = 100.0;
CGRect frame = CGRectMake(-radius, -radius,
self.frame.size.width + radius,
self.frame.size.height + radius);
if (CGRectContainsPoint(frame, point)) {
return self;
}
return nil;
}
(澄清后:)为了确保按钮被视为在父级范围内,您需要覆盖 pointInside:withEvent:
in父级包含按钮的框架.
Edit 2: (After clarification:) In order to ensure that the button is treated as being within the parent's bounds, you need to override pointInside:withEvent:
in the parent to include the button's frame.
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
if (CGRectContainsPoint(self.view.bounds, point) ||
CGRectContainsPoint(button.view.frame, point))
{
return YES;
}
return NO;
}
注意上面用于覆盖 pointInside 的代码并不完全正确.正如 Summon 在下面解释的那样,请执行以下操作:
Note the code just there for overriding pointInside is not quite correct. As Summon explains below, do this:
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
if ( CGRectContainsPoint(self.oversizeButton.frame, point) )
return YES;
return [super pointInside:point withEvent:event];
}
请注意,您很可能会使用 self.oversizeButton
作为此 UIView 子类中的 IBOutlet;然后您可以将有问题的超大按钮"拖动到有问题的特殊视图.(或者,如果由于某种原因你在一个项目中经常这样做,你会有一个特殊的 UIButton 子类,你可以查看这些类的子视图列表.)希望它有所帮助.
Note that you'd very likely do it with self.oversizeButton
as an IBOutlet in this UIView subclass; then you can just drag the "oversize button" in question, to, the special view in question. (Or, if for some reason you were doing this a lot in a project, you'd have a special UIButton subclass, and you could look through your subview list for those classes.) Hope it helps.
这篇关于超越 UIView 的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!