问题:按钮点击区域过小,想自己控制按钮的点击区域大小。(采用Runtime运行时)
解决:
import UIKit
import ObjectiveC.runtime
extension UIButton {
///提供多个运行时的key
struct RuntimeKey {
static let buttonKey = UnsafeRawPointer.init(bitPattern: "BTNKey".hashValue)
}
///需要扩充的边距
var hitTestEdgeInsets: UIEdgeInsets? {
set {
objc_setAssociatedObject(self, RuntimeKey.buttonKey!, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
get {
return objc_getAssociatedObject(self, RuntimeKey.buttonKey!) as? UIEdgeInsets ?? UIEdgeInsets.zero
}
}
///是否响应
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if UIEdgeInsetsEqualToEdgeInsets(hitTestEdgeInsets!, UIEdgeInsets.zero) || !isEnabled || isHidden {
return super.point(inside: point, with: event)
}
return UIEdgeInsetsInsetRect(bounds, hitTestEdgeInsets!).contains(point)
}
}
用法如下:
btn.hitTestEdgeInsets = UIEdgeInsets(top: -100, left: -100, bottom: -100, right: -100)