Swift: Expand UIButton’s clickable area

We all know the drill – there’s a button that doesn’t always detect touch events due to various reasons (being too small, having too thin symbol in it, etc).

Here’s an elegant way to solve this in Swift – what’s happening is that we’re “expanding” the clickable area around the button to treat touches within that area as button touch events:

extension UIButton {
  override public func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    var relativeFrame = self.bounds
    var hitTestEdgeInsets = UIEdgeInsetsMake(-44, -44, -44, -44)
    var hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitTestEdgeInsets)
    return CGRectContainsPoint(hitFrame, point)
  }
}

Leave a Reply

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