如何增加UIButton的Tap Area?

我使用UIButton自动布局。 当图像很小时,点击区域也很小。 我可以想象几种方法来解决这个问题:

  1. 增加图像大小,即在图像周围放置一个透明区域。 这并不好,因为当你定位图像时,你必须记住额外的透明边框。
  2. 使用CGRectInset并增加大小。 这不适用于自动布局,因为使用自动布局它将回退到原始图像大小。

除了上述两种方法之外,是否有更好的解决方案来增加UIButton的抽头区域?

您只需调整按钮的内容插入即可获得所需的大小。 在代码中,它将如下所示:

button.contentEdgeInsets = UIEdgeInsets(上:12,左:16,下:12,右:16)

//或者如果您特别想调整图像,请使用button.imageEdgeInsets

在界面构建器中,它将如下所示:

界面构建器

好简单。 创建自定义UIButton类。 然后覆盖pointInside …方法并根据需要更改值。

 #import "CustomButton.h" @implementation CustomButton -(BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event { CGRect newArea = CGRectMake(self.bounds.origin.x - 10, self.bounds.origin.y - 10, self.bounds.size.width + 20, self.bounds.size.height + 20); return CGRectContainsPoint(newArea, point); } @end 

每侧需要10点以上的触摸区域。

您可以在故事板中或通过代码设置按钮EdgeInsets。 按钮的大小和高度应该比设置为按钮的图像大。

注意:在Xcode8之后,设置内容插入在尺寸检查中可用 UIEdgeInseton UIButton

或者您也可以使用带有敲击手势的图像视图进行操作,同时在图像视图上进行操作。 确保在故事板上为imageview启用了用户交互function,以便手势正常工作。 使图像视图大于要在其上设置的图像并在其上设置图像。 现在将图像视图图像的模式设置为storyboard /界面构建器的中心。

使用带有点击操作的图像视图,并将图像设置为中心模式 您可以点按图片来执行操作。

希望它会有所帮助。

Swift 4•Xcode 9

您可以以编程方式选择

对于图像 –

 button.imageEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) 

标题 –

 button.titleEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) 

我确认Syed的解决方案即使使用自动布局也能正常工作。 这是Swift 4.x版本:

 import UIKit class BeepSmallButton: UIButton { // MARK: - Functions override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let newArea = CGRect( x: self.bounds.origin.x - 5.0, y: self.bounds.origin.y - 5.0, width: self.bounds.size.width + 10.0, height: self.bounds.size.height + 20.0 ) return newArea.contains(point) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } 

我不确定,但是应该有一种方法可以为任何UIView指定最小尺寸,这可能会解决您的额外工作问题。 但老实说,在图像周围添加额外的透明背景是最好的解决方案。