子视图超出父视图不响应解决办法

690 阅读1分钟

父视图中重写该方法 Objective-C

- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event {
    UIView * view = [super hitTest:point withEvent:event];
    if (view == nil) {
        for (UIView * subView in self.subviews) {
            // 将坐标系转化为自己的坐标系
            CGPoint tp = [subView convertPoint:point fromView:self];
            if (CGRectContainsPoint(subView.bounds, tp)) {
                view = subView;
            }
        }
    }
    return view;
}

Swift

    override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        var view = super.hitTest(point, withEvent: event)
        if view == nil {
            for subView in self.subviews {
                let tp = subView.convertPoint(point, fromView: self)
                if CGRectContainsPoint(subView.bounds, tp) {
                    view = subView
                }
            }
        }
        return view
    }

测试代码

   override func viewDidLoad() {
        super.viewDidLoad()
       let costemView = CustomView(frame: CGRectMake(100, 100 , 100, 100))
        self.view.addSubview(costemView)
        
        let button = UIButton(frame: CGRectMake(-20, -20, 40, 40))
        costemView.addSubview(button)
        button.backgroundColor = UIColor.lightGrayColor()
        button.addTarget(self, action: #selector(aaa), forControlEvents: .TouchUpInside)
    }
    
    func aaa() -> Void {
        print("dafd")
    }