swift 之超出父视图点击事件响应处理

实际开发中,常常遇到一些超出父视图的按钮:

例如:

swift 之超出父视图点击事件响应处理_第1张图片
Snip20180327_2.png

这是后的做法是遍历到响应事件的视图,将点击的坐标转化到父视图,并返回相应subView

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        
        if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01 ){
            return nil
        }
        let resultView  = super.hitTest(point, with: event)
        if resultView != nil {
            return resultView
        }else{   
            for subView in self.subviews.reversed() {
      // 这里根据层级的不同,需要遍历的次数可能不同,看需求来写,我写的例子是一层的
                let convertPoint : CGPoint = subView.convert(point, from: self)
                let hitView = subView.hitTest(convertPoint, with: event)
                if (hitView != nil) {
                    return hitView
                }
            }
        }
        return nil
    }


在让超出父视图的部分响应点击后,可能按钮还是不好点击,原因是按钮图片太小, 所以要扩大按钮响应时间的范围,


    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        var bounds = self.bounds
        let widthDelta = max(17 - bounds.width, 0)
        let heightDelta = max(17 - bounds.height, 0)
        bounds = bounds.insetBy(dx: -widthDelta, dy: -heightDelta)
        return bounds.contains(point)
    }

你可能感兴趣的:(swift 之超出父视图点击事件响应处理)