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

时间:2016-10-20 20:04:27

标签: swift xcode uitapgesturerecognizer

I have a set of 12 UIImageViews in my storyboard, and, for argument's sake, I want to get each one to print to logs "You just tapped image x", when the user taps on it, where x is the number of image tapped, from 1-12). So i need to detect which image is tapped, and do something depending on that information. What would be the best way to do this, in Swift 3 ?

(I assume 12 IBActions -treat them as button with an image on background- is really bad code. Also they need to be placed on specific positions on top of a background image, so cannot use UICollectionView to do this.) Thanks

3 个答案:

答案 0 :(得分:0)

这本身并不错,但如果您这样做,或者在每个ImageView上使用点按手势,您可能希望将逻辑部分分开。

您可以使用其他方法/视图来更好地管理此类事情,特别是如果这应该扩展,但是根据您的约束,这是我建议的:

将TapGestureRecognizers添加到您的imageViews或制作按钮,然后将所有操作连接到此:

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

答案 1 :(得分:0)

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

  • 为所有imageView设置userInteractionEnabledtrue
  • 为所有imageView设置-sequential- tag,例如image1.tag = 1,image2.tag = 2 ...依此类推。
  • 实施一个方法作为所有图片点击的目标,它应该类似于:

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

  • 创建-one单击手势并将已实现的方法分配给其选择器:

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

  • 最后,为您的所有图片添加tapGesture,例如:image1.addGestureRecognizer(tapGesture),image2.addGestureRecognizer(tapGesture)......依此类推。

希望这有帮助。

答案 2 :(得分:0)

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

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