【问题标题】:Tap detection UIImageView within UIStackView within UIScrollView在 UIScrollView 中的 UIStackView 中点击检测 UIImageView
【发布时间】:2018-04-17 15:54:43
【问题描述】:

我在水平 UIStackViews 中有几个 UIImageViews,包装在一个垂直 UIStackView 中,所有这些都包装在一个 UIScrollView 中。所有 UIxx 元素都选中了“启用用户交互”。我的 UIViewController 试图像这样捕捉水龙头:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {

        if touch.view is UIImageView {
            print("Touch began in image view")
        }
    }
    super.touchesBegan(touches, with:event)
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first{
        if touch.view is UIImageView {
            print("Touch ended in image view")
        }
    }
    super.touchesEnded(touches, with: event)
}

但是,无论我做什么,我都无法从堆栈视图中包含的 UIImageViews 中捕获触摸。然后什么也没有发生。不调用处理程序。在此之上还有另一个 UIView,它的反应很好。

附加图像中的视图布局

欢迎任何指针。

【问题讨论】:

  • 更进一步:必须向 UIScrollView 添加一个 UITapGestureRecognizer 以拦截对 UIImageViews 的触摸。让 tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapScrollView)) scrollView.addGestureRecognizer(tapGesture) @objc func tapScrollView(sender: UITapGestureRecognizer) { print("Tapped") }。现在需要识别被触摸的图像

标签: swift touch uistackview


【解决方案1】:

好的,答案就在这里。

1) 在viewDidLoad的UIScrollView中添加一个UITapGestureRecognizer

@IBOutlet weak var scrollView: UIScrollView!

...

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapScrollView))
scrollView.addGestureRecognizer(tapGesture)

2) 给每个 UIImageView 一个唯一的标签

3) 找到被点击的 UIImageView

@objc func tapScrollView(sender: UITapGestureRecognizer) {
    for stackView in self.scrollView.subviews[0].subviews[0].subviews {
        for imageView in stackView.subviews {
            let location = sender.location(in: imageView)
            if let hitImageView = imageView.hitTest(location, with: nil) {
                print("Tapped", hitImageView.tag)
            }
        }
    }
}

当然,正确的容器视图的识别取决于实现,所以在我的例子中是由

self.scrollView.subviews[0].subviews[0].subviews

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多