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

时间:2018-03-25 17:10:19

标签: ios swift uiview uibutton uigesturerecognizer

我希望能够用手指移动UIView

内部UIViewUIButton,当手指开始从视图内部区域拖动但在按钮外部时,一切都按预期工作,但是当手指开始从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
    }
}

1 个答案:

答案 0 :(得分:1)

你为什么使用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