Apple’s Human Interface guidelines recommend a minimum 44pt x 44pt
tappable area or all touchable elements, but sometimes you can’t make certain something that big in your layout, or you want to make it easier to tap something. We can create a custom subclass of UIButton to easily extend the tappable area and make the app much more user friendly:
import Foundation
import UIKit
class UIExtendedButton : UIButton {
// Override the hit test, extending the bounds by 30px in each direction
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// Compute the new bounding rectancle by extending by -30 in each direction:
let rect = UIEdgeInsetsInsetRect(self.bounds, UIEdgeInsetsMake(-30, -30, -30, -30))
// Check if it contains the tap coordinates.
return rect.contains(point)
}
}
You can also change the individual offsets for each of the edges of the touch rectangle, if you want. The signature for the UIEdgeInsetsMake
function is as follows. positive values will shrink the original box, and negative values will grow it:
UIEdgeInsetsMake(top, left, bottom, right)
Important Note: Make sure that the expanded touch areas of buttons aren’t overlapping. This could cause issues.