Created
April 19, 2019 04:57
-
-
Save pddkhanh/1398fa088716f19206c3442293013194 to your computer and use it in GitHub Desktop.
Extend touch area of UIControl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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