在UIScrollView

时间:2017-11-05 11:02:09

标签: swift touch uistackview

我在水平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,反应很好。

附加图像中的视图布局

任何指针欢迎。

View Layout

1 个答案:

答案 0 :(得分: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