bruno
bruno

Reputation: 2169

Can't touch UIButton behind UIScrollview

I have a UIButton behind a UIScrollview, and i want to be able to touch the button. Has it's obvious at this moment i can only perform actions on the UIScrollview, but i also want to be able to perform actions on the UIButton

Upvotes: 0

Views: 1210

Answers (2)

Hamish
Hamish

Reputation: 80781

"nothing is impossible" ... Sure, but it might be insanity.


If you want the UIScrollView to remain touchable to the user, you could try something similar to what Hemang suggests.

I would suggest sending the a signal to the UIButton's touchUpInside event directly through. For example, in your UIViewController:

@implementation ViewController {
    UIScrollView* scrollView;
    UITapGestureRecognizer* tapGesture;

    UIButton* button;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    button = [[UIButton alloc] initWithFrame:(CGRect){30, 30, 300, 300}];
    [button addTarget:self action:@selector(buttonPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    scrollView = [[UIScrollView alloc] initWithFrame:(CGRect){20, 20, 300, 500}];
    tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewWasTouched)];
    [scrollView addGestureRecognizer:tapGesture];
    [self.view addSubview:scrollView];


}

-(void) buttonPress {
    NSLog(@"Button press!");
}

-(void) scrollViewWasTouched {
    if (CGRectContainsPoint(button.frame, [tapGesture locationOfTouch:0 inView:self.view])) {
        [button sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
}

@end

I have no idea why you would ever want to do this though!


EDIT

I now learn that you want to do this as you want images in the scroll view to behave like buttons. I would suggest you simply replace your UIImageView objects with UIButton objects.

You can then just add the image to the UIButton directly:

[button setImage:image forState:UIControlStateNormal];

Upvotes: 1

Alexander Gaidukov
Alexander Gaidukov

Reputation: 759

You can override method

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView?

in superview of scrollView and Button. This method should return receiver for specific point. So in your case it should be something like that

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { 
if CGRectContainsPoint(button.frame, point) {
return button
}
return super.hitTest(post, withEvent: event)
}

Upvotes: 0

Related Questions