我知道这是一篇旧帖子,但我想出了类似的东西,希望它对其他人有用。我只是将我的 imageViews 存储在一个数组中,并将其分配给一个函数中的同一个手势识别器,以设置每个图像视图。
在我看来DidLoad():
imageViewList = [imageView, imageView2, imageView3]
setupImageViews(imageViews: imageViewList)
设置图像视图的功能:
func setupImageViews(imageViews: [UIImageView]) {
for imageView in imageViews {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
//set up image to be displayed with the right aspect
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
imageView.contentMode = .scaleAspectFit // OR .scaleAspectFill
imageView.clipsToBounds = true
}
}
在动作选择器 imageTapped() 中,您可以为所点击的任何图像视图设置相应的代码。
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
switch tapGestureRecognizer.view {
case imageView:
print("tapped Image View 1") //add your actions here
case imageView2:
print("tapped Image View 2") //add your actions here
case imageView3:
print("tapped Image View 3") //add your actions here
default:
print("Tap not detected")
}
_ = tapGestureRecognizer.view as! UIImageView
//additional code...
}