将UIButton的触摸限制在指定区域

时间:2015-09-07 10:55:22

标签: ios objective-c swift uibutton swift2

我确定这可能听起来像一个菜鸟问题但不知怎的我卡住了,我需要帮助。考虑我的uibutton,其背景图像具有偶然的可见边界,并且当点击时触摸按钮边界内部并且不仅仅是偶然的可见边界,这完全有意义。但是我想将其触摸限制在可见边界而不是整个按钮。请在附件中找到解释我想要的地方(绿色检查)触摸和不在哪里(红十字)的图像。提前谢谢你。

enter image description here

1 个答案:

答案 0 :(得分:3)

UIButton子类并实现pointInside:withEvent方法。 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/pointInside:withEvent

当系统想要知道为事件指定的点是否在您的视图中时,将调用此方法。如果是,则返回YES,否则返回NO。

您只需要一种方法来判断该点是否在您的UIButton点击区域中。当它返回YES时。

使用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;
}

您使用的矩形越多,制作的矩形越小,您的区域就越有针对性。如果你最终会使用太多东西,或者使用更好的东西。