Join the excitement of aviator game online and soar to new gaming levels.

Preserving a minimum tappable area for UIButton

One of the Apple Human Interface Guideline says:

Provide ample touch targets for interactive elements. Try to maintain a minimum tappable area of 44pt x 44pt for all controls.

(https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/)

But sometimes, your graphic designer only gives you a tiny image and:

  1. you don’t want to deal with the button insets in your layout
  2. you still want your users to have a reasonable hit zone

The solution is to override the func hitTest(_:, with:) -> UIView? method of the UIButton, so that it returns said button even if the tap if slightly out of bounds (as long as this matches the 44×44 points rule):

import UIKit
class MinimumTouchAreaButton: UIButton {
override func hitTest(_ point: CGPoint, with _: UIEvent?) -> UIView? {
guard !isHidden, isUserInteractionEnabled, alpha > 0 else {
return nil
}
let expandedBounds = bounds.insetBy(dx: min(bounds.width – 44.0, 0), dy: min(bounds.height – 44.0, 0))
return expandedBounds.contains(point) ? self : nil
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *