Skip to content

Instantly share code, notes, and snippets.

@simme
Last active January 19, 2018 09:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simme/118113fbd49e6713f6a65c2b03e22e09 to your computer and use it in GitHub Desktop.
Save simme/118113fbd49e6713f6a65c2b03e22e09 to your computer and use it in GitHub Desktop.
Extension to set an extended hitbox on UIButtons.
//
// UIBotton+hitBox.swift
//
// LICENSE: MIT
//
import UIKit
extension UIButton {
private struct AssociatedKeys {
static var hitBoxValue = "filibaba_hit_box"
}
var hitBox: UIEdgeInsets? {
get {
guard let value = objc_getAssociatedObject(self, &AssociatedKeys.hitBoxValue) as? NSValue else {
return nil
}
let insets = value.UIEdgeInsetsValue()
return insets
}
set {
if let newValue = newValue {
let value = NSValue(UIEdgeInsets: newValue)
objc_setAssociatedObject(self, &AssociatedKeys.hitBoxValue, value, .OBJC_ASSOCIATION_COPY_NONATOMIC)
} else {
objc_setAssociatedObject(self, &AssociatedKeys.hitBoxValue, nil, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
}
public override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
guard let hitBox = self.hitBox where self.enabled && !self.hidden else {
return super.pointInside(point, withEvent: event)
}
let relativeFrame = self.bounds
let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitBox)
return hitFrame.contains(point)
}
}
@simme
Copy link
Author

simme commented Aug 22, 2016

Usage:

// Needs to be negative to extend _outwards_.
myButton.hitBox = UIEdgeInsets(top: -16, left: -16, bottom: -16, right: -16)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment