遍历scrollView,找到被点击的imageView

Iterate through scrollView and find the clicked imageView

我有一个水平滚动的 ScrollView,它有很多 imageView。我想突出显示用户单击的 imageView,但我不确定如何执行此操作。我在图像中添加了点击手势:

let tap = UITapGestureRecognizer(target: self, action: #selector(imgTapped(_:)))

但我不确定在 imgTapped 函数中从这里做什么...我为每个 imageView 都有一个唯一的标签。

如有任何帮助,我们将不胜感激。

如果您有所有 imageViews 的集合,您可以这样做:

func imgTapped(_ sender: UIGestureRecognizer) {
    // get the tag for the clicked imageView
    guard let tag = sender.view?.tag else { return }

    let imageView = ImageViews.filter { [=10=].tag == tag }.first
}

否则,您可以遍历 scrollViews subviews,查看注释并查看代码中发生的情况:

func imgTapped(_ sender: UIGestureRecognizer) {
    // get the tag for the clicked imageView
    guard let tag = sender.view?.tag else { return }

    // iterate through your scrollViews subviews
    // and check if it´s an imageView
    for case let imageView as UIImageView in self.imageScrollView.subviews {
        // check if the tag matches the clicked tag
        if imageView.tag == tag {
            // this is the tag the user has clicked on
            // highlight it here
        }
    }
}