扩大按钮点击区域
很多时候,我们在使用按钮时,设计给的图标比较小,手指操作时点击效果不好,在不改变设计样式的同时,我们可以通过扩大按钮的点击区域,提高页面的交互性,方便用户的使用。
/**
UIButton 扩展
*/
extension UIButton {
private static var clickEdgeInsets = "clickEdgeInsets"
/// 扩充点击的范围
/// 使用方式 btn.enlargeEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
open var enlargeEdgeInsets: UIEdgeInsets? {
set {
objc_setAssociatedObject(self, &Self.clickEdgeInsets, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
get {
return objc_getAssociatedObject(self, &Self.clickEdgeInsets) as? UIEdgeInsets ?? UIEdgeInsets.zero
}
}
/// 重写系统方法修改点击区域
override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let inset = enlargeEdgeInsets else {
return super.point(inside: point, with: event)
}
var bounds = self.bounds
let x: CGFloat = -inset.left
let y: CGFloat = -inset.top
let width: CGFloat = bounds.width + inset.left + inset.right
let height: CGFloat = bounds.height + inset.top + inset.bottom
bounds = CGRect(x: x, y: y, width: width, height: height) // 负值是方法响应范围
return bounds.contains(point)
}
}
使用方式
/// 对按钮在上边、右边、下边、左边各自扩大20的点击区域
btn.enlargeEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)