2

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

Mohsin Khubaib Ahmed
  • 1,008
  • 16
  • 32

1 Answers1

3

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.

Rory McKinnel
  • 7,936
  • 2
  • 17
  • 28
  • i was looking for this method too. – Teja Nandamuri Sep 07 '15 at 11:12
  • something like this: http://codedmi.com/questions/1899974/uibutton-hit-area-is-too-big ? – Mohsin Khubaib Ahmed Sep 07 '15 at 11:16
  • 1
    Well that link shows how to use `hitTest` which you could use to test you code out. However the main thing is to implement `pointInside` as that is the method used to decide if a view or its children can handle the event or not. I would start by having rectangles that you allow. When its working you can then try and be more elaborate or use more rectangles but smaller ones. – Rory McKinnel Sep 07 '15 at 11:22