UIView的。 为什么在家长的范围之外的子视图没有接触到?

我有一个简单的 – 微不足道的UIView父/子层次结构。 一位家长(UIView)。 一个孩子(UIButton)。 父母的边界比其小,所以孩子的一部分超出了父母的边界框。

问题如下:父母的bbox外的孩子的那些部分不会接触到触摸。 只在父母的bbox内轻敲允许子button接收触摸。

有人可以请build议一个修复/解决方法?

UPDATE

对于那些下面的问题,这里是我实施的解决scheme@Bastians最好的答案:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { BOOL isInside = [super pointInside:point withEvent:event]; // identify the button view subclass UIButton *b = (UIButton *)[self viewWithTag:3232]; CGPoint inButtonSpace = [self convertPoint:point toView:b]; BOOL isInsideButton = [b pointInside:inButtonSpace withEvent:nil]; if (isInsideButton) { return isInsideButton; } // if (YES == isInsideButton) return isInside; } 

问题是响应者链。 当你触摸显示器时,它会从父母身边走到孩子的身边。

所以,当你触摸屏幕时,父母会看到触摸超出了自己的范围,所以孩子们甚至不会问。

这是做hitTest的函数。 如果你有你自己的UIView类,你可以覆盖它,并自己返回button。

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

根据苹果公司自己的文档 ,我发现最简单也是最可靠的方法就是覆盖hitTest:withEvent:在裁剪视图的超类中,如下所示:

 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { // Convert the point to the target view's coordinate system. // The target view isn't necessarily the immediate subview CGPoint pointForTargetView = [self.targetView convertPoint:point fromView:self]; if (CGRectContainsPoint(self.targetView.bounds, pointForTargetView)) { // The target view may have its view hierarchy, // so call its hitTest method to return the right hit-test view return [self.targetView hitTest:pointForTargetView withEvent:event]; } return [super hitTest:point withEvent:event]; } 

先决条件

UIView (名为container)中有一个UIButton (名为button1),并且button1部分位于容器边界之外。

问题

button1容器外的部分不会响应点击。

解答

从UIView子类化您的容器:

 class Container: UIView { override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { let closeButton = viewWithTag(10086) as! UIButton //<-- note the tag value if closeButton.pointInside(convertPoint(point, toView: closeButton), withEvent: event) { return true } return super.pointInside(point, withEvent: event) } } 

不要忘记给你的button1一个10086的标签

我手边有同样的问题。 您只需要覆盖:

– (BOOL)pointInside:(CGPoint)指向事件:(UIEvent *)事件

这里是一个自定义的UIView子类的工作代码,只是为了让它出界的孩子创build。

 @implementation ARQViewToRightmost // We should not need to override this one !!! /*-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { if ([self isInside:point]) return self; return nil; }*/ -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { if ([self isInside:point]) return YES; // That answer will make hitTest continue recursively probing the view's subviews for hit return NO; } // Check to see if the point is within the bounds of the view. We've extended the bounds to the max right // Make sure you do not have any other sibling UIViews to the right of this one as they will never receive events - (BOOL) isInside:(CGPoint)point { CGFloat maxWidth = CGFLOAT_MAX; CGRect rect = CGRectMake(0, 0, maxWidth, self.frame.size.height); if (CGRectContainsPoint(rect, point)) return YES; return NO; } @end