我在水平 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 布局
欢迎任何指点。
最佳答案
好的,答案在这里。
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/