Both solutions presented here do work ... under the right circumstances it is. But here are some gotchas you might run into.
First something not completely obvious:
- tapping has to be WITHIN the button, touching the button bounds slightly does NOT work. If a button is very small, there is a good chance most of your finger will be outside of the button and the tap won't work.
Specific to the solutions above:
SOLUTION 1 @Travis:
Use contentEdgeInsets to increase the button size without increasing the icon/text size, similar to adding padding
button.contentEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
This one is straight forward, increasing the button size increases the tap area.
- if you have set a height/width frame or constraint, obviously this doesn't do much, and will just distort or shift your icon/text around.
- the button size will be bigger. This has to be considered when laying out other views. (offset other views as necessary)
SOLUTION 2 @Syed Sadrul Ullah Sahad:
Subclass UIButton and override point(inside point: CGPoint, with event: UIEvent?) -> Bool
class BigAreaButton: UIButton {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return bounds.insetBy(dx: -20, dy: -20).contains(point)
}
}
This solution is great because it will allow you extend the tap area beyond the views bounds without changing the layout, but here are the catches:
- a parent view needs to have a background, putting a button into an otherwise empty ViewController without a background won't work.
- if the button is NESTED, all views up the view hierarchy need to either provide enough "space" or override point-in as well.
e.g.
---------
| |
|oooo |
|oXXo |
|oXXo |
|oooo | Button-X nested in View-o will NOT extend beyond View-o
---------