美文网首页
Swift-按钮扩大点击区域

Swift-按钮扩大点击区域

作者: SK丿希望 | 来源:发表于2019-07-23 11:31 被阅读0次

    注意: 如果(top/left/bottom/right)值>0向外扩大区域<0缩小区域

    btn.hw_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) 
    
    extension UIButton{
        
        // 改进写法【推荐】
        private struct RuntimeKey {
            static let clickEdgeInsets = UnsafeRawPointer.init(bitPattern: "clickEdgeInsets".hashValue)
            /// ...其他Key声明
        }
        /// 需要扩充的点击边距
        public var hw_clickEdgeInsets: UIEdgeInsets? {
            set {
                objc_setAssociatedObject(self, UIButton.RuntimeKey.clickEdgeInsets!, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
            }
            get {
                return objc_getAssociatedObject(self, UIButton.RuntimeKey.clickEdgeInsets!) as? UIEdgeInsets ?? UIEdgeInsets.zero
            }
        }
        // 重写系统方法修改点击区域
        open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            super.point(inside: point, with: event)
            var bounds = self.bounds
            if (hw_clickEdgeInsets != nil) {
                let x: CGFloat = -(hw_clickEdgeInsets?.left ?? 0)
                let y: CGFloat = -(hw_clickEdgeInsets?.top ?? 0)
                let width: CGFloat = bounds.width + (hw_clickEdgeInsets?.left ?? 0) + (hw_clickEdgeInsets?.right ?? 0)
                let height: CGFloat = bounds.height + (hw_clickEdgeInsets?.top ?? 0) + (hw_clickEdgeInsets?.bottom ?? 0)
                bounds = CGRect(x: x, y: y, width: width, height: height) //负值是方法响应范围
            }
            return bounds.contains(point)
        }
    }

    相关文章

      网友评论

          本文标题:Swift-按钮扩大点击区域

          本文链接:https://www.haomeiwen.com/subject/fflolctx.html