swift - UIScrollView 中的 UIStackView 中的点击检测 UIImageView

标签 swift touch uistackview

我在水平 UIStackView 中有几个 UIImageView,包裹在垂直 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)
}

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

附图中的 View 布局

欢迎任何指点。

View Layout

最佳答案

好的,答案在这里。

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)
            }
        }
    }
}

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

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

关于swift - UIScrollView 中的 UIStackView 中的点击检测 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120799/

相关文章:

ios - 如何防止将相同的字符串添加到存储的数组中

internet-explorer - 如何在Google Analytics(分析)中识别Microsoft Surface流量?

ios - 触摸移动 UIButton

swift - 导航栏标题中的多个重叠图像

ios - 如果删除和添加相同的 View ,UIStackView 不会填充

ios - 在 UItableView 中处理 UItextfield 的委托(delegate)

ios - 当传输编码的响应 header 值被分块时,NSURLCache 不起作用

swift - 如何为UIDocument添加通知观察者?

android - 播放动画时禁用屏幕上的触摸事件

swift - UIButton 标题未显示在 UIStackView 内