Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing events on a custom UIControl

I am subclassing UIControl to compose a custom control that contains different standard controls.

For this discussion let's assume that my custom UIControl contains a UIButton only.

What I would like to achieve is that clicking anywhere in the custom UIControl generates a click event for that custom UIControl. The standard behavior is that the UIButton will process and consume (i.e. not forward) the click event.

As subclassing UIButton is discouraged, I can't really find a straightforward way of achieving this.

Any suggestions?

like image 610
Beav Avatar asked Mar 05 '11 13:03

Beav


2 Answers

I came up with a simple solution that doesn't need subclassing of the UIButton.

In the action method defined for the UIButton's TouchUpInside control event, I have added the following line of code:

[self sendActionsForControlEvents:UIControlEventTouchUpInside];

This results in the TouchUpInside control event being called, when clicking anywhere in the custom UIControl.

like image 108
Beav Avatar answered Dec 05 '22 18:12

Beav


UIViews have a method called -hitTest:withEvent: that the event system uses to crawl the view hierarchy and dispatch events to subviews. If you want a parent view to gobble up all events that might otherwise be dispatched to its subviews, just override the parent's -hitTest:withEvent: with something like the following:

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
  if(CGRectContainsPoint([self bounds], point)){
    return self;
  }
  return [super hitTest:point withEvent:event];
}
like image 22
jemmons Avatar answered Dec 05 '22 19:12

jemmons