【问题标题】:Tap area ridiculously small for UIButtonUIButton 的点击区域小得离谱
【发布时间】:2018-02-03 21:02:20
【问题描述】:

我有一个这样创建的 UIButton:

let closeButton = UIButton(type: .System)
closeButton.backgroundColor = UIColor(r: 92, g: 92, b: 118, alpha: 1)
closeButton.setImage(UIImage(named: "closeCross")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: .Normal)
closeButton.tintColor = UIColor.whiteColor()
closeButton.imageEdgeInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)

closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
closeButton.frame = CGRectMake(messageView.frame.maxX - 30, 0, 20, 20)
closeButton.center.y = messageView.bounds.midY

问题是只有当您距离UIButton 的中心一个像素时才会触发点击。我设置的图像是一个交叉的png X

即使我点击十字(但不完全在中间,感谢模拟器的精确度),它也不起作用。

我不明白。背景不清楚。无论我是否更改内容/图像边缘插图都不会改变任何事情。无论我是否使用图像渲染模式都不会改变任何事情。

【问题讨论】:

  • 您是否尝试手动设置按钮的框架?还是更改按钮类型?
  • closeButton.frame 打印出什么?
  • 刚刚用框架更新了帖子
  • 打印出(x : 345, y : 10, width : 20, height : 20)

标签: ios swift uibutton


【解决方案1】:

保持 UIbutton 的大小至少为 44x44 的最佳做法。 https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/LayoutandAppearance.html

通过为每个交互元素提供足够的间距,使人们可以轻松地与内容和控件进行交互。为可点击控件提供大约 44 x 44 点的命中目标。

所以我会将您的框架设置为大于 20pts,那么您的图像 20pts 的尺寸是多少?是否会在按钮之外进行剪辑,请检查 clipToBounds 是否设置为 yes。

还有一种更激进的方法,那就是创建一个 UIButton 的子类,触摸面积至少为 44。

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGFloat widthDelta = 44.0 - self.bounds.size.width;
    CGFloat heightDelta = 44.0 - self.bounds.size.width;
    CGRect largerBounds = CGRectInset(self.bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    return CGRectContainsPoint(largerBounds, point);
}

另一件事是使用reveal(http://revealapp.com/)调查按钮

【讨论】:

  • 你不需要透露,它包含在新的 XCode 版本中。试试调试器面板旁边的按钮:imgur.com/0KVy8nR
  • 大约在 Xcode 12 之前,他们可能已经完成了这个功能! =P 我发现它远没有揭示那么有用,但这是我个人的看法。还值得注意的是,您必须为揭露付费。
【解决方案2】:

这实际上是我修复它的方法:

closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
closeButton.frame = CGRectMake(noConnectionMessageView.frame.maxX - 40, 0, 40, 40)

【讨论】:

  • 打败了我。负插图意味着图像实际上看起来比目标区域大。
【解决方案3】:

只有当 UIButton 上没有标题和图像时才会发生这种情况。如果您不想添加标题,则有一个 hack...

只需添加一个空格作为标题文本。按钮的整个区域都会开始响应。

它奇迹般地为我工作。

【讨论】:

    猜你喜欢
    • 2018-04-22
    • 2010-10-22
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多