自定义 UIControl 不适用于 UITapGestureRecognizer

问题描述 投票:0回答:1

UITapGestureRecognizer
没有添加到视图中时,
UIButton
CustomControl
都会收到
.touchUpInside
事件。但是,当
UITapGestureRecognizer
添加到视图中时,只有
UIButton
可以接收
.touchUpInside
事件。如何配置自定义
UIControl
来响应这种情况下的手势?

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let uiButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        uiButton.backgroundColor = .red
        uiButton.addTarget(self, action: #selector(onUIButtonClick), for: .touchUpInside)
        view.addSubview(uiButton)
        
        let customButton = CustomControl(frame: CGRect(x: 200, y: 100, width: 100, height: 100))
        customButton.backgroundColor = .blue
        customButton.addTarget(self, action: #selector(onCustomControlClick), for: .touchUpInside)
        view.addSubview(customButton)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
        view.addGestureRecognizer(tapGesture)
    }
    
    @objc func onTap() {
        debugPrint("onTap")
    }
    
    @objc func onUIButtonClick() {
        debugPrint("onUIButtonClick")
    }
    
    @objc func onCustomControlClick() {
        debugPrint("onCustomControlClick")
    }
}

class CustomControl: UIControl {
}
ios swift uigesturerecognizer uicontrol
1个回答
0
投票
class CustomControl: UIControl {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        if let touch = touches.first {
            let touchPoint = touch.location(in: self)
            
            // Check if the touch point is within the bounds of your control
            if bounds.contains(touchPoint) {
                sendActions(for: .touchUpInside)
            }
        }
    }
}

通过此更改,您的

CustomControl
将手动检查触摸事件,如果在其边界内发生触摸事件,它将发出 .touchUpInside 事件,模仿 UIButton 的行为。

© www.soinside.com 2019 - 2024. All rights reserved.