1

Pretty simple question, perhaps not so simple answer though:

I've got a clear view which needs to receive touches. Underneath this is a UIButton, which I also want to receive touches (for reasons I won't go into, it has to be underneath). In the case where the button is pressed, I don't want the clear view to receive the touches.

How can I do this?

EDIT:

Final Solution:

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


    for (UIView * view in self.subviews)
    {
        if ([view isKindOfClass:[UIButton class]]) {
            CGPoint pointInButton = [view convertPoint:point fromView:self];
            if ([view pointInside:pointInButton withEvent:event]) {
                return view;
            }
        }
    }
    return [super hitTest:point withEvent:event];
}
Jordan Smith
  • 10,310
  • 7
  • 68
  • 114
  • Have you tried setting `userInteractionEnabled` to false for your clear view? – aroth Jan 04 '12 at 02:33
  • @aroth I need the clear view to receive touches too. Sorry should have been more specific in the question (which I'll edit now). – Jordan Smith Jan 04 '12 at 02:34

1 Answers1

2

Give the clear view a reference to the UIButton. Override the clear view's pointInside:withEvent: method. In your override, check whether the point is inside the button (by sending pointInside:withEvent: to the button). If the point is in the button, return NO. If the point is outside the button, return [super pointInside:point withEvent:event].

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • 1
    Additional discussion here: http://stackoverflow.com/questions/1694529/allowing-interaction-with-a-uiview-under-another-uiview – aroth Jan 04 '12 at 02:49
  • Thanks!! This is a great answer. I'm a bit stuck getting it working - any chance you'd be able to say why the code I'm using won't work (I've added it to my question)? – Jordan Smith Jan 04 '12 at 03:37
  • Aha... fixed with this line: CGPoint pointInButton = [view convertPoint:point fromView:self]; Thanks :) – Jordan Smith Jan 04 '12 at 03:46