cookiemonsta cookiemonsta - 1 year ago 98
Swift Question

Restricting UIButton's touch to assigned area

Im sure this may sound as a noob question but somehow Im stuck and I need help here. Consider my uibutton whose background image has a haphazard visible boundary and when clicked takes touch inside the buttons bounds and not exclusively in the haphazard visible boundary, which totally makes sense. However I want to restrict its touch to the visible boundary and not the entire button. Please find attached herewith the image that explains where I'd like (green check) the touch and where not (red cross). Thank you in advance for this.

enter image description here

Answer Source

Subclass UIButton and implement the pointInside:withEvent method.

This will be called when the system wants to know if the point given for the event is inside your view. Simply return YES if it is or NO if its not.

All you need is a way of deciding if the point is in your UIButton click zone or not. When it is return YES.

Something like the following which uses an array of CGRects:

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

      // Only pass through of the point is in a specific area
      BOOL ret=NO;

      for (NSValue *value in self.passThroughAreas){
          CGRect rect=value.CGRectValue;
          if (CGRectContainsPoint(rect, point)){
              // Its in one of our pass through areas. Let the events pass.

    return ret;

The more rectangles you use and the smaller you make them the more targeted your area can be. Or use something fancier if you are going to end up using too many.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download