Vins
Vins

Reputation: 1944

addSubview outside the view

I have a viewcontroller that via "[self.view addSubview: secondView.view]," adds a second view. The problem is that the second view is added outside half.

secondView = [[SecondView alloc] initWithFrame: CGRectMake (-160, 0, 320, 460)];
[self.view addSubview: secondView.view]; "

I have noticed, however, that the part before the 0 (-160) is not interagibile. Is this normal? is there a way to solve?

Thank you!

Upvotes: 0

Views: 1268

Answers (2)

Mark
Mark

Reputation: 639

You can allow subviews to receive touches outside of the parent's bounds by overriding pointInside:withEvent: for the parent view.

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    BOOL pointInside = NO;

    // step through our subviews' frames that exist out of our bounds
    for (UIView *subview in self.subviews)
    {
        if(!CGRectContainsRect(self.bounds, subview.frame) && [subview pointInside:[self convertPoint:point toView:subview] withEvent:event])
        {
            pointInside = YES;
            break;
        }
    }

    // now check inside the bounds
    if(!pointInside)
    {
         pointInside = [super pointInside:point withEvent:event];
    }

    return pointInside;
}

Upvotes: 6

sergio
sergio

Reputation: 69047

I fear that given the way the UIResponder chain works, what you want is not directly possible (the superview will only pass to its subviews the events that it recognizes as affecting itself).

On the other hand, if you really need to have this view outside of its parent's frame, you could associate a gesture recognizer (reference) to the subview. Indeed, gesture recognizers are handled outside the normal touch event dispatching and it should work.

Try this for a tap:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[secondView addGestureRecognizer:singleTap];

Upvotes: 1

Related Questions