【问题标题】:Make view draggable but not tappable使视图可拖动但不可点击
【发布时间】:2018-11-21 15:19:09
【问题描述】:

我的视图控制器中有一个标签,我在 viewDidLoad 中设置了这样的标签:

var label: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    label = UILabel()
    view.add(label)
    label.frame = CGRect(x: 0, y, 0, width: 20, height: 20)
    label.text = "A"

    let recognizer = UIPanGestureRecognizer(target: self, action: #selector(didDrag(_:))
    label.addGestureRecognizer(recognizer)
    label.isUserInteractionEnabled = true
}

我希望标签是可拖动的,所以我这样实现了didDrag

@objc func didDrag(_ gesture: UIPanGestureRecognizer) {
    let center = label.center
    let translation = gesture.translation(in: view)
    label.center = CGPoint(x: center.x + translation.x, y: center.y + translation.y)
    gesture.setTranslation(.zero, in: view)
}

它工作得很好,我可以拖动我的标签。

但是,如果标签位于我视图中的按钮上方并且我尝试点击该按钮,则该按钮不会被触摸。我试过了:

label.isUserInteractionEnabled = false // then I can't also drag around
recognizer.cancelsTouchesInView = false // nothing changes
label.isMultipleTouchEnabled = false // nothing changes

知道如何让标签的平移识别器通过/忽略单击或双击,但仍然可以拖动它吗?

如果它是重复的,我可以删除这个问题,但我没有找到任何其他完全相同的问题。

编辑

以下Pass taps through a UIPanGestureRecognizer,到目前为止我发现的最接近的问题,我也尝试过:

recognizer.delaysTouchesBegan = true
recognizer.maximumNumberOfTouches = 1
recognizer.cancelsTouchesInView = true

但不幸的是,它没有用。

更新 该视图有各种各样的按钮和文本字段,因此实际上不可能与它们中的每一个进行比较,主要是因为还有包含按钮的堆栈视图,有时它们存在而某些东西不存在。

【问题讨论】:

  • cancelsTouchesInView = true 是默认行为,尝试将其设置为false
  • 刚试过recognizer.cancelsTouchesInView = false。仍然没有任何变化。不过,谢谢。

标签: ios swift uipangesturerecognizer


【解决方案1】:

经过思考,我想出了可能可行的解决方案。这个想法是玩弄触摸事件。每个视图都有一组方法,例如touchesBegan()touchesMoved() 等。现在您可以做的是,当调用 touchesBegan 时,您可以检查正在发生的触摸的位置,以及该位置是否包含在按钮的框架中,手动调用函数。

这是伪代码,您可以了解这个概念。未经测试,但根据我的经验,类似的东西应该可以工作

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    touches.forEach { touch in 
        let touchLocation = touch.location(in: myButton) // that may need to be self instead of myButton 
        if myButton.frame.contains($0.location) {
             //invoke button method here
        }
    }
}

【讨论】:

  • 我有很多不同的按钮和文本字段。我必须与每个子视图以及每个子视图的每个子视图进行比较。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
相关资源
最近更新 更多