In my application I have a UIButton that is quite small, so I thought about increasing the hit area of it.
I found an extension for that:
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
}
}
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?
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)
}
}
Now the button is tappable 30 points outside its visible background.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With