Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Instinct would say "subclass UIButton", but UIButton is actually a class cluster (ie, the actual type of object transparently changes depending on what kind of button you want to make), which makes it supremely difficult to subclass. Short of rewriting UIButton, there's not much you can do on that approach.</p> <p>When I needed to solve an almost identical problem, I came up with a view that uses composition to display a proxy UIView, but still allow for touch interception. Here's how it works:</p> <pre><code>@interface MyView : UIView { UIView * visibleView; } - (id) initWithFrame:(CGRect)frame controlClass:(Class)class; @end @implementation MyView - (id) initWithFrame:(CGRect)frame controlClass:(Class)class { if (self = [super initWithFrame:frame]) { CGRect visibleViewFrame = frame; visibleViewFrame.origin = CGPointZero; visibleView = [[class alloc] initWithFrame:visibleViewFrame]; [visibleView setUserInteractionEnabled:NO]; [self addSubview:visibleView]; [self setUserInteractionEnabled:YES]; [self setBackgroundColor:[UIColor clearColor]]; } return self; } - (void) dealloc { [visibleView removeFromSuperview]; [visibleView release], visibleView = nil; [super dealloc]; } - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (someCondition == YES) { [visibleView touchesBegan:touches withEvent:event]; } } //and similar methods for touchesMoved:, touchesEnded:, etc @end </code></pre> <p>The basic idea to this is that you're embedding the button (or whatever) into a container class (similar to what you described in your question). However, you're disabling interaction on the button, which means that when a user taps the button, the tap event will "fall through" the button and into the buttons containing superview (in this, your MyView instance). From there, you can process the touch appropriately. If you want the button to "respond" to the touch, just allow the button to do so by sending the appropriate UIResponder message. (You <em>might</em> need to re-enable userInteractionEnabled on the visibleView first, though. I'm unsure of that.)</p> <p>As I stated above, I have used this approach (not this exact implementation, but this pattern) quite successfully, when I needed to have a button on the interface, but also capture the UITouch object itself.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload