当手指在该视图内的 UIButton 上时,触摸时拖动 UIView 不起作用

Dragging UIView on touch not working when finger is on UIButton inside that View

我希望能够用手指UIView四处移动。

UIView 内部是 UIButton,当手指开始从视图内部区域拖动但在按钮外部区域时一切正常,但是当手指从 UIButton 视图开始拖动时没有移动.

所以基本上我需要像 delaysContentTouches 这样的东西可用于 UIScrollView

如何阻止 UIButton 窃取触摸?请注意,我希望 UIButton 仍可点击。

表示问题的示例代码:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let testView = View(frame: CGRect(x: 10.0, y: 10.0, width: 200.0, height: 200.0))
        testView.backgroundColor = .blue
        view.addSubview(testView)

        let button = UIButton()
        testView.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("button", for: .normal)
        button.backgroundColor = .red

        button.leadingAnchor.constraint(equalTo: testView.leadingAnchor).isActive = true
        button.trailingAnchor.constraint(equalTo: testView.trailingAnchor).isActive = true
        button.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
        button.centerYAnchor.constraint(equalTo: testView.centerYAnchor).isActive = true
    }
}

class View: UIView {
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        guard let touch = touches.first else { return }
        let touchPoint = touch.location(in: self)

        self.frame.origin.x += touchPoint.x
        self.frame.origin.y += touchPoint.y
    }
}

为什么要使用 touchesMoved。使用平移手势。这就是他们的目的。另外,我也能够触摸按钮

@objc func panGestureHandler(panGesture recognizer: UIPanGestureRecognizer) {

if let thisView = recognizer.view {

  if recognizer.state == .began {
    someCentre = thisView.center // store old button center
  } else if  recognizer.state == .failed || recognizer.state == .cancelled {
    thisView.center = someCentre! // restore button center
  } else {
    let location = recognizer.location(in: view) // get pan location
    thisView.center = location // set button to where finger is
  }
}}

在视图中加载 -

let panGesture = UIPanGestureRecognizer(target: self, action: selector(self.panGestureHandler(panGesture:)))
panGesture.minimumNumberOfTouches = 1
testView.addGestureRecognizer(panGesture)
someCentre = testView.center