UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTapTap:)];
[self.view1 addGestureRecognizer:tapGesture];
[self.view2 addGestureRecognizer:tapGesture];
[tapGesture release];
在上面的代码中,只能识别view2上的点击。如果我注释掉第三行,那么点击view1会被识别。如果我是对的,你只能使用手势识别器一次,我不确定这是一个错误还是它只是需要一些更多的文档。
我知道这是一个旧帖子,但我认为类似的东西,希望它对其他人有用。我简单地将我的imageViews存储在一个数组中,并将其分配给一个函数中的相同手势识别器来设置每个图像视图。
在我的viewDidLoad():
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
}
}
在动作选择器imagetapping()中,您可以为所选中的任何图像视图设置相应的代码。
@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...
}