April 21, 2010

iPhone: Subviews in UIButtons block the touch, unless...

If you add a UIView or other UIView subclass to a UIButton, the UIView object will block touches/clicks on the UIButton. There's a simple fix to ensure that subviews in your UIButton don't interfere. In the following case, I have a subclass of UIView that loads an image from the web (WebImage), that's created inside a subclass of UIButton:
WebImage *thumb = [[WebImage alloc] initWithFrame:CGRectMake(1, 1, 94, 94) andImageUrl:@"http://mysite.com/thumbnail.png"];
[self addSubview:thumb];
thumb.userInteractionEnabled = NO;
thumb.exclusiveTouch = NO;
[thumb release]; 
All you need to do is set userInteractionEnabled and exclusiveTouch to NO or FALSE, and the subview will no longer block your button.

3 comments:

  1. Thanks for the post. It makes sense now, but was kinda counter intuitive to set user interaction to NO on sub views, in order to make the UIButton container view work with user interaction. :/

    ReplyDelete
  2. Thanks Thanks Thanks!!! That was a real saver...

    ReplyDelete