Mohsin Khubaib Ahmed
Mohsin Khubaib Ahmed

Reputation: 1018

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

Upvotes: 2

Views: 136

Answers (1)

Rory McKinnel
Rory McKinnel

Reputation: 8014

Subclass UIButton and implement the pointInside:withEvent method. https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/pointInside:withEvent:

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.
              ret=YES;
              break;
          }
      }

    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.

Upvotes: 3

Related Questions