如何在Swift中扩展特定UIButton的点击区域? [英] how can I expand the hit area of a specific UIButton in Swift?
本文介绍了如何在Swift中扩展特定UIButton的点击区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序中,我有一个UIButton
,它很小,所以我考虑增加它的点击范围.
In my application I have a UIButton
that is quite small, so I thought about increasing the hit area of it.
我找到了这个扩展名:
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
}
}
但是当我使用它时,我应用程序中的每个按钮都有较大的点击区域.我只想将其增加到一个specialButton
-我该怎么做?
but when I use it, every button in my app has a bigger hit area. I want to increase it to only one specialButton
- how can I do it?
推荐答案
请勿扩展点击范围;缩小绘图区域.将按钮设为UIButton的子类,然后在该子类中实现rect
方法,如下所示:
Don't expand the hit area; shrink the drawing area. Make the button a subclass of UIButton, and in that subclass, implement rect
methods, along these lines:
class MyButton : UIButton {
override func contentRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 30, dy: 30)
}
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 30, dy: 30)
}
}
现在该按钮可以在其可见背景之外点击30点.
Now the button is tappable 30 points outside its visible background.
这篇关于如何在Swift中扩展特定UIButton的点击区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文