swift - 遍历scrollView,找到点击的imageView

标签 swift imageview scrollview uitapgesturerecognizer

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

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

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

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

最佳答案

如果您拥有所有 imageView 的集合,您可以执行以下操作:

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

    let imageView = ImageViews.filter { $0.tag == tag }.first
}

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

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

关于swift - 遍历scrollView,找到点击的imageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43812894/

相关文章:

ios - 如何检索特定 View 的高度?

java - ImageView 中的背景图片导致崩溃

ios - 如何在iPhone中获取手指触摸的x和y位置后设置ImageView的位置

使用 fragment 的 Android 功能区菜单

xcode - UISplitViewController 从详细 View 呈现当前上下文

swift - 标签栏下的栏,如 Flipboard、Swift

swift 标签只剩下边框

ios - 如何在swift中使用 ImageView 生成随机图像

android - ScrollView 及其 subview 如何控制滚动

Android 2.2 使用 ACTION_UP 而 2.1 不使用(在嵌套 ScrollView 中)。我使用的是旧错误吗?