193

I have a question dealing with UIButton and its hit area. I am using the Info Dark button in interface builder, but I am finding that the hit area is not large enough for some people's fingers.

Is there a way to increase the hit area of a button either programmatically or in Interface Builder without changing the size of the InfoButton graphic?

4

36 回答 36

137

由于我使用的是背景图像,因此这些解决方案都不适合我。这是一个解决方案,它做了一些有趣的 Objective-c 魔法,并提供了一个使用最少代码的解决方案。

首先,添加一个UIButton覆盖命中测试的类别,并添加一个用于扩展命中测试框架的属性。

UIButton+Extensions.h

@interface UIButton (Extensions)

@property(nonatomic, assign) UIEdgeInsets hitTestEdgeInsets;

@end

UIButton+Extensions.m

#import "UIButton+Extensions.h"
#import <objc/runtime.h>

@implementation UIButton (Extensions)

@dynamic hitTestEdgeInsets;

static const NSString *KEY_HIT_TEST_EDGE_INSETS = @"HitTestEdgeInsets";

-(void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
    NSValue *value = [NSValue value:&hitTestEdgeInsets withObjCType:@encode(UIEdgeInsets)];
    objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIEdgeInsets)hitTestEdgeInsets {
    NSValue *value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS);
    if(value) {
        UIEdgeInsets edgeInsets; [value getValue:&edgeInsets]; return edgeInsets;
    }else {
        return UIEdgeInsetsZero;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }

    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);

    return CGRectContainsPoint(hitFrame, point);
}

@end

添加此类后,您需要做的就是设置按钮的边缘插图。请注意,我选择添加插图,因此如果要使命中区域更大,则必须使用负数。

[button setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -10, -10, -10)];

注意:请记住在您的类中导入类别 ( #import "UIButton+Extensions.h")。

于 2012-10-25T11:08:58.353 回答
78

只需在界面生成器中设置图像边缘插入值。

于 2011-04-22T13:44:21.247 回答
64

这是在 Swift 中使用 Extensions 的优雅解决方案。根据 Apple 的人机界面指南 ( https://developer.apple.com/ios/human-interface-guidelines/visual-design/layout/ ) ,它为所有 UIButtons 提供了至少 44x44 点的命中区域

斯威夫特 2:

private let minimumHitArea = CGSizeMake(44, 44)

extension UIButton {
    public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        // if the button is hidden/disabled/transparent it can't be hit
        if self.hidden || !self.userInteractionEnabled || self.alpha < 0.01 { return nil }

        // increase the hit frame to be at least as big as `minimumHitArea`
        let buttonSize = self.bounds.size
        let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
        let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
        let largerFrame = CGRectInset(self.bounds, -widthToAdd / 2, -heightToAdd / 2)

        // perform hit test on larger frame
        return (CGRectContainsPoint(largerFrame, point)) ? self : nil
    }
}

斯威夫特 3:

fileprivate let minimumHitArea = CGSize(width: 100, height: 100)

extension UIButton {
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // if the button is hidden/disabled/transparent it can't be hit
        if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil }

        // increase the hit frame to be at least as big as `minimumHitArea`
        let buttonSize = self.bounds.size
        let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
        let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
        let largerFrame = self.bounds.insetBy(dx: -widthToAdd / 2, dy: -heightToAdd / 2)

        // perform hit test on larger frame
        return (largerFrame.contains(point)) ? self : nil
    }
}
于 2014-12-29T04:58:43.443 回答
51

您还可以子类化UIButton或自定义UIView并使用以下内容覆盖point(inside:with:)

斯威夫特 3

override func point(inside point: CGPoint, with _: UIEvent?) -> Bool {
    let margin: CGFloat = 5
    let area = self.bounds.insetBy(dx: -margin, dy: -margin)
    return area.contains(point)
}

Objective-C

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat margin = 5.0;
    CGRect area = CGRectInset(self.bounds, -margin, -margin);
    return CGRectContainsPoint(area, point);
}
于 2012-12-20T18:02:57.337 回答
35

这是 Swift 3.0 中 Chase 的 UIButton+Extensions。


import UIKit

private var pTouchAreaEdgeInsets: UIEdgeInsets = .zero

extension UIButton {

    var touchAreaEdgeInsets: UIEdgeInsets {
        get {
            if let value = objc_getAssociatedObject(self, &pTouchAreaEdgeInsets) as? NSValue {
                var edgeInsets: UIEdgeInsets = .zero
                value.getValue(&edgeInsets)
                return edgeInsets
            }
            else {
                return .zero
            }
        }
        set(newValue) {
            var newValueCopy = newValue
            let objCType = NSValue(uiEdgeInsets: .zero).objCType
            let value = NSValue(&newValueCopy, withObjCType: objCType)
            objc_setAssociatedObject(self, &pTouchAreaEdgeInsets, value, .OBJC_ASSOCIATION_RETAIN)
        }
    }

    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        if UIEdgeInsetsEqualToEdgeInsets(self.touchAreaEdgeInsets, .zero) || !self.isEnabled || self.isHidden {
            return super.point(inside: point, with: event)
        }

        let relativeFrame = self.bounds
        let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.touchAreaEdgeInsets)

        return hitFrame.contains(point)
    }
}

要使用它,您可以:

button.touchAreaEdgeInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
于 2015-08-14T04:12:27.550 回答
19

我建议将自定义类型的 UIButton 放在信息按钮的中心。将自定义按钮的大小调整为您希望点击区域的大小。从那里你有两个选择:

  1. 检查自定义按钮的“高亮显示触摸”选项。白光会出现在信息按钮上,但在大多数情况下,用户的手指会遮住它,他们只会看到外面的光。

  2. 为信息按钮设置一个 IBOutlet,为自定义按钮设置两个 IBAction,一个用于“Touch Down”,一个用于“Touch Up Inside”。然后在 Xcode 中让 touchdown 事件将 info 按钮的 highlight 属性设置为 YES,touchupinside 事件将 highlight 属性设置为 NO。

于 2009-05-04T04:24:52.417 回答
19

不要backgroundImage用你的图像设置属性,设置imageView属性。另外,请确保您已imageView.contentMode设置为UIViewContentModeCenter.

于 2010-11-06T04:45:30.547 回答
14

我在 Swift 3 上的解决方案:

class MyButton: UIButton {

    override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let relativeFrame = self.bounds
        let hitTestEdgeInsets = UIEdgeInsetsMake(-25, -25, -25, -25)
        let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitTestEdgeInsets)
        return hitFrame.contains(point)
    }
}
于 2017-08-01T11:36:17.640 回答
12

给出的答案没有错;但是我想扩展jlarjlar 的答案,因为它具有惊人的潜力,可以为其他控件(例如 SearchBar)的相同问题增加价值。这是因为由于 pointInside 附加到 UIView,因此可以对任何控件进行子类化以改善触摸区域。该答案还显示了如何实施完整解决方案的完整示例。

为您的按钮(或任何控件)创建一个新的子类

#import <UIKit/UIKit.h>

@interface MNGButton : UIButton

@end

接下来覆盖子类实现中的 pointInside 方法

@implementation MNGButton


-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    //increase touch area for control in all directions by 20
    CGFloat margin = 20.0;
    CGRect area = CGRectInset(self.bounds, -margin, -margin);
    return CGRectContainsPoint(area, point);
}


@end

在您的故事板/xib 文件中选择有问题的控件并打开身份检查器并输入您的自定义类的名称。

按钮

在包含按钮的场景的 UIViewController 类中,将按钮的类类型更改为子类的名称。

@property (weak, nonatomic) IBOutlet MNGButton *helpButton;

将您的故事板/xib 按钮链接到属性 IBOutlet,您的触摸区域将被扩展以适合子类中定义的区域。

除了与CGRectInsetCGRectContainsPoint方法一起覆盖 pointInside 方法之外,还应该花时间检查CGGeometry以扩展任何 UIView 子类的矩形触摸区域。您还可以在 NSHipster 找到有关 CGGeometry 用例的一些不错的提示

例如,可以使用上面提到的方法使触摸区域变得不规则,或者简单地选择使宽度触摸区域是水平触摸区域的两倍:

CGRect area = CGRectInset(self.bounds, -(2*margin), -margin);

注意:替换任何 UI 类控件在扩展不同控件(或任何 UIView 子类,如 UIImageView 等)的触摸区域时应该会产生类似的结果。

于 2014-09-08T16:40:58.777 回答
10

这对我有用:

UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
// set the image (here with a size of 32 x 32)
[button setImage: [UIImage imageNamed: @"myimage.png"] forState: UIControlStateNormal];
// just set the frame of the button (here 64 x 64)
[button setFrame: CGRectMake(xPositionOfMyButton, yPositionOfMyButton, 64, 64)];
于 2010-05-12T08:24:42.740 回答
7

不要改变 UIButton 的行为。

@interface ExtendedHitButton: UIButton

+ (instancetype) extendedHitButton;

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

@end

@implementation ExtendedHitButton

+ (instancetype) extendedHitButton {
    return (ExtendedHitButton *) [ExtendedHitButton buttonWithType:UIButtonTypeCustom];
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGRect relativeFrame = self.bounds;
    UIEdgeInsets hitTestEdgeInsets = UIEdgeInsetsMake(-44, -44, -44, -44);
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitTestEdgeInsets);
    return CGRectContainsPoint(hitFrame, point);
}

@end
于 2013-12-16T22:29:25.707 回答
7

我通过 swizzling 使用更通用的方法-[UIView pointInside:withEvent:]。这允许我修改任何的命中测试行为UIView,而不仅仅是UIButton.

通常,一个按钮被放置在一个容器视图中,这也限制了命中测试。例如,当一个按钮位于容器视图的顶部并且您想向上扩展触摸目标时,您还必须扩展容器视图的触摸目标。

@interface UIView(Additions)
@property(nonatomic) UIEdgeInsets hitTestEdgeInsets;
@end

@implementation UIView(Additions)

+ (void)load {
    Swizzle(self, @selector(pointInside:withEvent:), @selector(myPointInside:withEvent:));
}

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

    if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || self.hidden ||
       ([self isKindOfClass:UIControl.class] && !((UIControl*)self).enabled))
    {
        return [self myPointInside:point withEvent:event]; // original implementation
    }
    CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.hitTestEdgeInsets);
    hitFrame.size.width = MAX(hitFrame.size.width, 0); // don't allow negative sizes
    hitFrame.size.height = MAX(hitFrame.size.height, 0);
    return CGRectContainsPoint(hitFrame, point);
}

static char hitTestEdgeInsetsKey;
- (void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
    objc_setAssociatedObject(self, &hitTestEdgeInsetsKey, [NSValue valueWithUIEdgeInsets:hitTestEdgeInsets], OBJC_ASSOCIATION_RETAIN);
}

- (UIEdgeInsets)hitTestEdgeInsets {
    return [objc_getAssociatedObject(self, &hitTestEdgeInsetsKey) UIEdgeInsetsValue];
}

void Swizzle(Class c, SEL orig, SEL new) {

    Method origMethod = class_getInstanceMethod(c, orig);
    Method newMethod = class_getInstanceMethod(c, new);

    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    else
        method_exchangeImplementations(origMethod, newMethod);
}
@end

这种方法的好处是您甚至可以通过添加用户定义的运行时属性在 Storyboards 中使用它。可悲的是,UIEdgeInsets它不能直接作为一种类型使用,但由于CGRect它还包含一个带有四个的结构,CGFloat因此通过选择“Rect”并填写如下值可以完美地工作{{top, left}, {bottom, right}}

于 2012-11-20T14:11:34.127 回答
6

我在 Swift 中使用以下类,还可以启用 Interface Builder 属性来调整边距:

@IBDesignable
class ALExtendedButton: UIButton {

    @IBInspectable var touchMargin:CGFloat = 20.0

    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        var extendedArea = CGRectInset(self.bounds, -touchMargin, -touchMargin)
        return CGRectContainsPoint(extendedArea, point)
    }
}
于 2015-06-23T12:51:04.657 回答
5

好吧,您可以将您的 UIButton 放在一个透明且稍大的 UIView 中,然后像在 UIButton 中一样在 UIView 实例上捕获触摸事件。这样,您仍然可以使用按钮,但触摸区域更大。如果用户触摸视图而不是按钮,您将必须手动处理按钮的选定和突出显示状态。

其他可能性涉及使用 UIImage 而不是 UIButton。

于 2009-04-30T18:59:15.857 回答
5

我已经能够以编程方式增加信息按钮的点击区域。“i”图形不改变比例,并保持在新按钮框架的中心。

在 Interface Builder 中,信息按钮的大小似乎固定为 18x19[*]。通过将其连接到 IBOutlet,我能够在代码中更改其帧大小而不会出现任何问题。

static void _resizeButton( UIButton *button )
{
    const CGRect oldFrame = infoButton.frame;
    const CGFloat desiredWidth = 44.f;
    const CGFloat margin = 
        ( desiredWidth - CGRectGetWidth( oldFrame ) ) / 2.f;
    infoButton.frame = CGRectInset( oldFrame, -margin, -margin );
}

[*]:更高版本的 iOS 似乎增加了信息按钮的点击区域。

于 2009-10-13T23:55:17.617 回答
5

这是我的Swift 3解决方案(基于这篇博文:http: //bdunagan.com/2010/03/01/iphone-tip-larger-hit-area-for-uibutton/

class ExtendedHitAreaButton: UIButton {

    @IBInspectable var hitAreaExtensionSize: CGSize = CGSize(width: -10, height: -10)

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        let extendedFrame: CGRect = bounds.insetBy(dx: hitAreaExtensionSize.width, dy: hitAreaExtensionSize.height)

        return extendedFrame.contains(point) ? self : nil
    }
}
于 2017-01-20T15:00:19.867 回答
3

就是这么简单:

class ChubbyButton: UIButton {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return bounds.insetBy(dx: -20, dy: -20).contains(point)
    }
}

这就是全部。

于 2019-09-22T20:00:17.173 回答
3

通过覆盖继承的 UIButton 实现。

斯威夫特 2.2

// don't forget that negative values are for outset
_button.hitOffset = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
...
class UICustomButton: UIButton {
    var hitOffset = UIEdgeInsets()

    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        guard hitOffset != UIEdgeInsetsZero && enabled && !hidden else {
            return super.pointInside(point, withEvent: event)
        }
        return UIEdgeInsetsInsetRect(bounds, hitOffset).contains(point)
    }
}
于 2016-06-17T22:22:43.620 回答
3

基于上面 giaset 的回答(我找到了最优雅的解决方案),这里是 swift 3 版本:

import UIKit

fileprivate let minimumHitArea = CGSize(width: 44, height: 44)

extension UIButton {
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // if the button is hidden/disabled/transparent it can't be hit
        if isHidden || !isUserInteractionEnabled || alpha < 0.01 { return nil }

        // increase the hit frame to be at least as big as `minimumHitArea`
        let buttonSize = bounds.size
        let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
        let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
        let largerFrame = bounds.insetBy(dx: -widthToAdd / 2, dy: -heightToAdd / 2)

        // perform hit test on larger frame
        return (largerFrame.contains(point)) ? self : nil
    }
}
于 2016-09-16T14:58:22.367 回答
3

Chase 的自定义命中测试实现为 UIButton 的子类。用Objective-C编写。

它似乎对构造函数都init有效。buttonWithType:对于我的需要,它是完美的,但由于子类化UIButton可能很麻烦,我很想知道是否有人对它有问题。

CustomeHitAreaButton.h

#import <UIKit/UIKit.h>

@interface CustomHitAreaButton : UIButton

- (void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets;

@end

CustomHitAreaButton.m

#import "CustomHitAreaButton.h"

@interface CustomHitAreaButton()

@property (nonatomic, assign) UIEdgeInsets hitTestEdgeInsets;

@end

@implementation CustomHitAreaButton

- (instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        self.hitTestEdgeInsets = UIEdgeInsetsZero;
    }
    return self;
}

-(void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
    self->_hitTestEdgeInsets = hitTestEdgeInsets;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }
    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);
    return CGRectContainsPoint(hitFrame, point);
}

@end
于 2016-06-16T17:48:29.990 回答
2

永远不要覆盖类别中的方法。子类按钮和覆盖- pointInside:withEvent:。例如,如果您的按钮边小于 44 像素(推荐作为最小可点击区域),请使用:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    return (ABS(point.x - CGRectGetMidX(self.bounds)) <= MAX(CGRectGetMidX(self.bounds), 22)) && (ABS(point.y - CGRectGetMidY(self.bounds)) <= MAX(CGRectGetMidY(self.bounds), 22));
}
于 2014-06-06T16:50:09.150 回答
2

WJBackgroundInsetButton.h

#import <UIKit/UIKit.h>

@interface WJBackgroundInsetButton : UIButton {
    UIEdgeInsets backgroundEdgeInsets_;
}

@property (nonatomic) UIEdgeInsets backgroundEdgeInsets;

@end

WJBackgroundInsetButton.m

#import "WJBackgroundInsetButton.h"

@implementation WJBackgroundInsetButton

@synthesize backgroundEdgeInsets = backgroundEdgeInsets_;

-(CGRect) backgroundRectForBounds:(CGRect)bounds {
    CGRect sup = [super backgroundRectForBounds:bounds];
    UIEdgeInsets insets = self.backgroundEdgeInsets;
    CGRect r = UIEdgeInsetsInsetRect(sup, insets);
    return r;
}

@end
于 2012-08-03T02:09:28.303 回答
2

我为此目的制作了一个图书馆

您可以选择使用UIView类别,无需子类化

@interface UIView (KGHitTesting)
- (void)setMinimumHitTestWidth:(CGFloat)width height:(CGFloat)height;
@end

或者您可以继承您的 UIView 或 UIButton 并设置minimumHitTestWidth和/或minimumHitTestHeight. 然后,您的按钮命中测试区域将由这 2 个值表示。

就像其他解决方案一样,它使用该- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event方法。该方法在 iOS 执行命中测试时被调用。这篇博文很好地描述了 iOS 命中测试的工作原理。

https://github.com/kgaidis/KGHitTestingViews

@interface KGHitTestingButton : UIButton <KGHitTesting>

@property (nonatomic) CGFloat minimumHitTestHeight; 
@property (nonatomic) CGFloat minimumHitTestWidth;

@end

您也可以只继承并使用 Interface Builder 而无需编写任何代码: 在此处输入图像描述

于 2015-05-17T00:50:41.940 回答
1

我对 tableviewcell.accessoryView 内的按钮使用这个技巧来扩大它的触摸区域

#pragma mark - Touches

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch                  = [touches anyObject];
    CGPoint location                = [touch locationInView:self];
    CGRect  accessoryViewTouchRect  = CGRectInset(self.accessoryView.frame, -15, -15);

    if(!CGRectContainsPoint(accessoryViewTouchRect, location))
        [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch                  = [touches anyObject];
    CGPoint location                = [touch locationInView:self];
    CGRect  accessoryViewTouchRect  = CGRectInset(self.accessoryView.frame, -15, -15);

    if(CGRectContainsPoint(accessoryViewTouchRect, location) && [self.accessoryView isKindOfClass:[UIButton class]])
    {
        [(UIButton *)self.accessoryView sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
    else
        [super touchesEnded:touches withEvent:event];
}
于 2012-08-08T15:07:31.383 回答
1

我刚刚在 swift 2.2 中移植了 @Chase解决方案

import Foundation
import ObjectiveC

private var hitTestEdgeInsetsKey: UIEdgeInsets = UIEdgeInsetsZero

extension UIButton {
    var hitTestEdgeInsets:UIEdgeInsets {
        get {
            let inset = objc_getAssociatedObject(self, &hitTestEdgeInsetsKey) as? NSValue ?? NSValue(UIEdgeInsets: UIEdgeInsetsZero)
            return inset.UIEdgeInsetsValue()
        }
        set {
            let inset = NSValue(UIEdgeInsets: newValue)
            objc_setAssociatedObject(self, &hitTestEdgeInsetsKey, inset, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    public override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        guard !UIEdgeInsetsEqualToEdgeInsets(hitTestEdgeInsets, UIEdgeInsetsZero) && self.enabled == true && self.hidden == false else {
            return super.pointInside(point, withEvent: event)
        }
        let relativeFrame = self.bounds
        let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitTestEdgeInsets)
        return CGRectContainsPoint(hitFrame, point)
    }
}

你可以这样使用

button.hitTestEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)

有关任何其他参考,请参阅https://stackoverflow.com/a/13067285/1728552

于 2016-08-03T17:07:06.603 回答
1

我看到很多解决方案要么没有达到目标,要么需要指定一些固定的插图来添加。这是一个简单UIView子类的解决方案,它将视图的命中矩形扩展到至少44 x 44;如果任一维度已经大于该维度,则它不会人为地填充该维度。

这可确保按钮始终具有建议的最小触摸尺寸 44 x 44,而无需任何手动配置、计算或图像填充:

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let minimumTouchSize: CGFloat = 44.0
    let center: CGPoint = .init(x: self.bounds.midX, y: self.bounds.midY)

    let minimumHitRect: CGRect =
        .init(center: center, size: .zero)
        .insetBy(
            dx: -minimumTouchSize / 2.0,
            dy: -minimumTouchSize / 2.0
        )

    let fullHitRect = self.bounds.union(minimumHitRect)

    return fullHitRect.contains(point)
}
于 2020-06-10T17:18:13.653 回答
1

@antoine 为 Swift 4 格式化的答案

final class ExtendedHitButton: UIButton {
    
    override func point( inside point: CGPoint, with event: UIEvent? ) -> Bool {
        let relativeFrame = self.bounds
        let hitTestEdgeInsets = UIEdgeInsets(top: -44, left: -44, bottom: -44, right: -44) // Apple recommended hit target
        let hitFrame = relativeFrame.inset(by: hitTestEdgeInsets)
        return hitFrame.contains( point );
    }
}
于 2019-03-18T22:06:53.457 回答
1

与 Zhanserik 类似,具有可变扩展名并针对 Swift 4.2 进行了更新:

class ButtonWithExtendedHitArea: UIButton {

    var extention: CGFloat

    required init(extendBy: CGFloat) {
        extention = extendBy

        super.init(frame: .zero)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let relativeFrame = self.bounds
        let hitTestEdgeInsets = UIEdgeInsets(top: -extention, left: -extention, bottom: -extention, right: -extention)
        let hitFrame = relativeFrame.inset(by: hitTestEdgeInsets)
        return hitFrame.contains(point)
    }

}
于 2019-02-22T02:41:03.603 回答
0

我玩这个游戏太晚了,但想权衡一种可能解决您问题的简单技术。这是我的一个典型的编程 UIButton 片段:

UIImage *arrowImage = [UIImage imageNamed:@"leftarrow"];
arrowButton = [[UIButton alloc] initWithFrame:CGRectMake(15.0, self.frame.size.height-35.0, arrowImage.size.width/2, arrowImage.size.height/2)];
[arrowButton setBackgroundImage:arrowImage forState:UIControlStateNormal];
[arrowButton addTarget:self action:@selector(onTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
[arrowButton addTarget:self action:@selector(onTouchDown:) forControlEvents:UIControlEventTouchDown];
[arrowButton addTarget:self action:@selector(onTap:) forControlEvents:UIControlEventTouchUpInside];
[arrowButton addTarget:self action:@selector(onTouchUp:) forControlEvents:UIControlEventTouchDragExit];
[arrowButton setUserInteractionEnabled:TRUE];
[arrowButton setAdjustsImageWhenHighlighted:NO];
[arrowButton setTag:1];
[self addSubview:arrowButton];

我正在为我的按钮加载一个透明的 png 图像并设置背景图像。我正在根据 UIImage 设置框架,并为视网膜缩放 50%。好吧,也许你同意或不同意,但如果你想让命中区域更大,让自己头疼:

我做什么,在 Photoshop 中打开图像,只需将画布大小增加到 120% 并保存。实际上,您刚刚使用透明像素使图像更大。

只有一种方法。

于 2014-11-06T18:29:38.640 回答
0

我遵循了 Chase 的响应,它工作得很好,当你创建的区域太大时,一个问题是大于按钮被取消选择的区域(如果区域不是更大)它不会调用 UIControlEventTouchUpInside 事件的选择器.

我认为大小超过 200 任何方向或类似的东西。

于 2013-04-12T15:07:28.053 回答
0

@jlajlar 上面的答案似乎很好而且很简单,但与 Xamarin.iOS 不匹配,因此我将其转换为 Xamarin。如果您在 Xamarin iOS 上寻找解决方案,这里有:

public override bool PointInside (CoreGraphics.CGPoint point, UIEvent uievent)
{
    var margin = -10f;
    var area = this.Bounds;
    var expandedArea = area.Inset(margin, margin);
    return expandedArea.Contains(point);
}

您可以将此方法添加到要覆盖 UIView 或 UIImageView 的类中。这很好用:)

于 2015-03-20T01:07:36.827 回答
0

这个 Swift 版本允许你为所有 UIButtons 定义一个最小点击大小。至关重要的是,它还可以处理隐藏 UIButtons 的情况,许多答案都忽略了这一点。

extension UIButton {
    public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        // Ignore if button hidden
        if self.hidden {
            return nil
        }

        // If here, button visible so expand hit area
        let hitSize = CGFloat(56.0)
        let buttonSize = self.frame.size
        let widthToAdd = (hitSize - buttonSize.width > 0) ? hitSize - buttonSize.width : 0
        let heightToAdd = (hitSize - buttonSize.height > 0) ? hitSize - buttonSize.height : 0
        let largerFrame = CGRect(x: 0-(widthToAdd/2), y: 0-(heightToAdd/2), width: buttonSize.width+widthToAdd, height: buttonSize.height+heightToAdd)
        return (CGRectContainsPoint(largerFrame, point)) ? self : nil
    }
}
于 2016-06-21T01:58:29.270 回答
0

没有一个答案对我来说是完美的,因为我在那个按钮上使用了背景图片和标题。此外,按钮将随着屏幕大小的变化而调整大小。

相反,我通过使 png 透明区域更大来扩大点击区域。

于 2016-04-13T08:10:18.860 回答
-1
  • 不覆盖类别或扩展
  • 每个指南至少 44x44

我的看法:

open class MinimumTouchAreaButton: UIButton {
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard !self.isHidden, self.isUserInteractionEnabled, self.alpha > 0 else { return nil }
        let expandedBounds = bounds.insetBy(dx: min(bounds.width - 44, 0), dy: min(bounds.height - 44, 0))
        return expandedBounds.contains(point) ? self : nil
    }
} 
于 2017-07-19T04:02:45.350 回答
-1

迅速:

override func viewWillAppear(animated: Bool) {
        self.sampleButton.frame = CGRectInset(self.sampleButton.frame, -10, -10);
    }
于 2016-07-20T09:53:51.250 回答
-2
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let inset = UIEdgeInsets(top: -adjustHitY * 0.5, left: -adjustHitX * 0.5, bottom: -adjustHitY * 0.5, right: -adjustHitX * 0.5)
    return UIEdgeInsetsInsetRect(bounds, inset).contains(point)
}
于 2017-05-24T16:50:45.890 回答