【问题标题】:Dragging UIView on touch not working when finger is on UIButton inside that View当手指在该视图内的 UIButton 上时,触摸时拖动 UIView 不起作用
【发布时间】:2018-09-03 20:02:21
【问题描述】:

我希望能够用手指在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
    }
}

【问题讨论】:

    标签: ios swift uiview uibutton uigesturerecognizer


    【解决方案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
    

    【讨论】:

    • 它有效,感谢您的帮助,但我仍然不明白为什么 touchesMoved 在这种情况下不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多