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
答案 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是一种更好的方法来实现你想要的。但是,您需要:
userInteractionEnabled
至true
。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)......依此类推。希望这有帮助。
答案 2 :(得分:0)
我认为拥有12个按钮根本不是一个坏主意。为每个标签分配1-12的标签,并将它们连接到同一个IBAction。
@IBAction func didTapImageButton(button: UIButton) {
print("You just tapped image \(button.tag)")
}