Skip to content

Instantly share code, notes, and snippets.

@pddkhanh
Created April 19, 2019 04:57
Show Gist options
  • Save pddkhanh/1398fa088716f19206c3442293013194 to your computer and use it in GitHub Desktop.
Save pddkhanh/1398fa088716f19206c3442293013194 to your computer and use it in GitHub Desktop.
Extend touch area of UIControl
import UIKit
private var pTouchAreaEdgeInsets: Int = 0
extension UIControl {
var touchAreaEdgeInsets: UIEdgeInsets {
get {
if let value = objc_getAssociatedObject(self, &pTouchAreaEdgeInsets) as? NSValue {
var edgeInsets: UIEdgeInsets = .zero
value.getValue(&edgeInsets)
return edgeInsets
} else {
return .zero
}
}
set(newValue) {
var newValueCopy = newValue
let objCType = NSValue(uiEdgeInsets: .zero).objCType
let value = NSValue(&newValueCopy, withObjCType: objCType)
objc_setAssociatedObject(self, &pTouchAreaEdgeInsets, value, .OBJC_ASSOCIATION_RETAIN)
}
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if touchAreaEdgeInsets == .zero || !self.isEnabled || self.isHidden {
return super.point(inside: point, with: event)
}
let relativeFrame = self.bounds
let hitFrame = relativeFrame.inset(by: touchAreaEdgeInsets)
return hitFrame.contains(point)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment