更小的活动区域为圆形自定义按钮

时间:2022-08-07 19:34:22

I have a custom button (which uses a a circled shaped image as its custom view). The problem is: the active area of the custom button is much too large, if I tap at least 100 pixels outside the button, it still gets registered as a tap on the button. This results in accidental taps.

我有一个自定义按钮(它使用一个圆圈形状的图像作为它的自定义视图)。问题是:自定义按钮的活动区域太大了,如果我在按钮外面点击至少100个像素,它仍然会被注册为点击按钮。这导致了意外的轻击。

Note:- I don't want to reduce size of button as it is already bigger that minimum requirement. I want to reduce tappable space.

注意:-我不想减少按钮的大小,因为它已经比最低要求大。我想减少可拖空间。

How can I reduce the active area on these buttons?

如何减少这些按钮上的活动区域?

1 个解决方案

#1


2  

If your button isn't already a subclass of UIButton, it will have to be to achieve this. You can override pointInside:withEvent: to alter the "touchable" area to any arbitrary shape you want. A subclass that simply alters the hit box's insets might look something like this:

如果你的按钮还不是UIButton的子类,它就必须实现这个功能。您可以覆盖pointInside:withEvent:将“可触摸”区域更改为任意形状。一个简单地改变点击框内嵌件的子类可能看起来是这样的:

// --HEADER--
@interface TouchInsetButton : UIButton
@property (nonatomic, assign) UIEdgeInsets touchInsets;
@end

// --IMPLEMENTATION--
@implementation TouchInsetButton
@synthesize touchInsets = _touchInsets;

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGRect modifiedHitBox = UIEdgeInsetsInsetRect([self bounds], _touchInsets);
    return CGRectContainsPoint(modifiedHitBox, point);
}

@end

Just note that, as you noticed, UIButtons normally use a bounding box that's slightly larger than their bounds. Just using this subclass without setting any insets will result in a button that only accepts hits that are completely within the button's bounds.

请注意,正如您所注意到的,UIButtons通常使用一个略大于其界限的边框。只使用这个子类而不设置任何insets就会导致一个按钮,只接受完全在按钮范围内的点击。

#1


2  

If your button isn't already a subclass of UIButton, it will have to be to achieve this. You can override pointInside:withEvent: to alter the "touchable" area to any arbitrary shape you want. A subclass that simply alters the hit box's insets might look something like this:

如果你的按钮还不是UIButton的子类,它就必须实现这个功能。您可以覆盖pointInside:withEvent:将“可触摸”区域更改为任意形状。一个简单地改变点击框内嵌件的子类可能看起来是这样的:

// --HEADER--
@interface TouchInsetButton : UIButton
@property (nonatomic, assign) UIEdgeInsets touchInsets;
@end

// --IMPLEMENTATION--
@implementation TouchInsetButton
@synthesize touchInsets = _touchInsets;

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGRect modifiedHitBox = UIEdgeInsetsInsetRect([self bounds], _touchInsets);
    return CGRectContainsPoint(modifiedHitBox, point);
}

@end

Just note that, as you noticed, UIButtons normally use a bounding box that's slightly larger than their bounds. Just using this subclass without setting any insets will result in a button that only accepts hits that are completely within the button's bounds.

请注意,正如您所注意到的,UIButtons通常使用一个略大于其界限的边框。只使用这个子类而不设置任何insets就会导致一个按钮,只接受完全在按钮范围内的点击。