UIButton ignores touch if you touch it where there's no image alpha. Can I change it to respond to touch on its entire bounds?
4 Answers
I actually do this all the time where I put the image with transparent background into a UIImageView
and then put a UIButton
with its backgroundColor
set to [UIColor clearColor]
on top of the image. This way, especially with small images, I can make the "invisible" button larger and easier to press for the user.
UIButton ignores touch if you touch it where there's no image alpha. Can I change it to respond to touch on its entire bounds?
One easy way that I think still works is to set the background color to something that's only mostly transparent. An alpha that's very small but still greater than 0.1 should look transparent but still respond to touches.
Otherwise, yes, you can override -hitTest:withEvent:
such that it returns YES even if the touched area is transparent.
-
-
You'd probably want to at least check that the point is inside the button's bounds.– CalebJun 28, 2013 at 16:17
-
1OK will do - thanks. Right now the transparency workaround seems to be working fine. Thanks! Jun 28, 2013 at 16:20
Just to follow on the suggestion by Caleb to override hitTest and taking inspiration from Soroush Khanlou, this makes any UIButton subclass respond to any touch that happens on the frame:
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard
isUserInteractionEnabled,
!isHidden,
alpha >= 0.01,
self.point(inside: point, with: event)
else {return nil}
for subview in subviews.reversed() {
let convertedPoint = subview.convert(point, from: self)
if let candidate = subview.hitTest(convertedPoint, with: event) {
return candidate
}
}
return self
}
-
Hi Franco, could you explain how you use the hit function or where to implement it? I am trying to use it to ignore the transparent part of the button instead.– STerrierAug 29, 2019 at 0:51
-
1You have to subclass UIButton and override the hitTest method in your subclass implementation. Then assign your UIButton subclass to the button in Interface Builder if you're using storyboards, or just instantiate a copy of your subclass if you build your UI in code. Aug 29, 2019 at 10:40
-
I have a UIView
extension that will help. Just have your button call this method.
extension UIView {
public func makeBackgroundAlpha002() {
backgroundColor = UIColor(white: 0, alpha: 0.02)
}
}
Why alpha 0.02? If you read the Apple Documentation, they explain the magic during hit testing.
This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01.