刚才加的iOS群分享了一份OC版本的代码,大概看了一下觉得改成Swift3.0的也很简单 于是就花几分钟动手改了一下。
import UIKit
fileprivate var rectNameKey:(Character?,Character?,Character?,Character?)
extension UIButton
{
func setEnlargeEdgeWith(top:CGFloat,right:CGFloat,bottom:CGFloat,left:CGFloat)
{
objc_setAssociatedObject(self, &rectNameKey.0, top, .OBJC_ASSOCIATION_COPY_NONATOMIC)
objc_setAssociatedObject(self, &rectNameKey.1, right, .OBJC_ASSOCIATION_COPY_NONATOMIC)
objc_setAssociatedObject(self, &rectNameKey.2, bottom, .OBJC_ASSOCIATION_COPY_NONATOMIC)
objc_setAssociatedObject(self, &rectNameKey.3, left, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let topEdge = objc_getAssociatedObject(self, &rectNameKey.0) as? CGFloat,
let rightEdge = objc_getAssociatedObject(self, &rectNameKey.1) as? CGFloat,
let bottomEdge = objc_getAssociatedObject(self, &rectNameKey.2) as? CGFloat,
let leftEdge = objc_getAssociatedObject(self, &rectNameKey.3) as? CGFloat
{
return CGRect(x: bounds.origin.x - leftEdge, y: bounds.origin.y - topEdge, width: bounds.width + leftEdge + rightEdge, height: bounds.height + topEdge + bottomEdge).contains(point) ? self : nil
}
return super.hitTest(point, with: event)
}
}
即拿即用。