扩大UIbutton的点击范围,需要重写方法两个方法中的任意一个即可
1,override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool
2, override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
extension UIButton {
struct hitTestKey {
static let hitTestEdgeInsetsKey = UnsafeRawPointer.init(bitPattern: "hitTestEdgeInsetsKey".hashValue)
}
var hitTestEdgeInsets: UIEdgeInsets {
set {
objc_setAssociatedObject(self, hitTestKey.hitTestEdgeInsetsKey!, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
get {
if let rs = objc_getAssociatedObject(self, hitTestKey.hitTestEdgeInsetsKey!) as? UIEdgeInsets {
return rs
}
return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
}
}
override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let rect = self.bounds.inset(by: self.hitTestEdgeInsets)
print("event")
if rect.contains(point) {
return self
}else {
return nil
}
}
override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let rect = self.bounds.inset(by: self.hitTestEdgeInsets)
print("inside")
return rect.contains(point)
}
}