如何在用户点击视图控制器中的多个 UIImages 之一时打印 "image x tapped"? (Swift 3)

How to print "image x tapped" when user taps on one of many UIImages in the View Controller? (Swift 3)

我的故事板中有一组 12 个 UIImageView,并且,为了论证,我想让每个人都打印到日志 "You just tapped image x",当用户点击它时,其中 x 是数字点击图像的数量,从 1-12)。所以我需要检测哪个图像被点击,并根据该信息做一些事情。在 Swift 3 中,最好的方法是什么?

(我假设 12 个 IBActions - 将它们视为带有背景图像的按钮 - 是非常糟糕的代码。此外,它们需要放置在背景图像顶部的特定位置,因此不能使用 UICollectionView 来执行此操作。 ) 谢谢

它本身并不是糟糕的代码,但如果您这样做,或者在每个 ImageView 上使用点击手势,您可能希望分离出那部分逻辑。

您可以使用其他 approaches/views 来更好地管理此类事情,尤其是在需要扩展的情况下,但考虑到您的限制,我建议这样做:

将 TapGestureRecognizers 添加到您的 imageView 或将它们设为按钮,然后将它们的所有操作连接到此:

@IBAction func phoneWasPressed(sender: AnyObject) {
    guard let tappedImageView = sender as? UIImageView else {
        return
    }

    switch tappedImageView {
    case imageView1:
        //do something
    case imageView2:
        // do something else
    //etc.
    default:
        break
    }
    switch sender
}

首先,我认为使用 collectionView 是实现您想要的效果的更好方法。但是,您需要:

  • 将所有图像视图的 userInteractionEnabled 设置为 true
  • 为所有 imageView 设置 -sequential- tag,例如 image1.tag = 1,image2.tag = 2 ... 等等。
  • 实现一个方法成为你所有图片点击的目标,它应该类似于这样:

    func imageViewTapped(imageView: UIImageView) { print("You just tapped image (imageView.tag)") }

  • 创建一个单击手势并将实现的方法分配给它的选择器:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))

  • 最后,为您的所有图像添加 tapGesture,例如:image1.addGestureRecognizer(tapGesture)、image2.addGestureRecognizer(tapGesture)...等等。

希望这对您有所帮助。

我不认为拥有 12 个按钮是个坏主意。从 1 到 12 为它们每个分配一个标签,并将它们连接到相同的 IBAction。

@IBAction func didTapImageButton(button: UIButton) {
    print("You just tapped image \(button.tag)")
}