Skip to content

Instantly share code, notes, and snippets.

@richellis
Created December 15, 2017 00:39
Show Gist options
  • Save richellis/98bef22fcbef6cc3f5f6e3ed35c70f1a to your computer and use it in GitHub Desktop.
Save richellis/98bef22fcbef6cc3f5f6e3ed35c70f1a to your computer and use it in GitHub Desktop.
/// Expands the touch target of the button to be at least as large as the minimum iOS guidelines.
class ExpandedHitButton: UIButton {
let minimumHitSize: CGSize
/// Creates an instance of `ExpandedHitButton`.
///
/// - Parameters:
/// - minimumHitSize: Size of the minimum hit rectangle, centered at the bounds midpoint. Default is 44x44
/// points (iOS Guidelines).
init(minimumHitSize: CGSize = CGSize(width: 44, height: 44)) {
self.minimumHitSize = minimumHitSize
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let halfWidth = minimumHitSize.width / 2
let halfHeight = minimumHitSize.height / 2
let hitTestEdgeInsets = UIEdgeInsets(top: -halfHeight, left: -halfWidth, bottom: -halfHeight, right: -halfWidth)
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let centerRectZero = CGRect(origin: center, size: .zero)
let minimumHitRect = UIEdgeInsetsInsetRect(centerRectZero, hitTestEdgeInsets)
let hitRect = bounds.union(minimumHitRect)
return hitRect.contains(point)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment