如何识别调用了哪个点击手势识别器?

how to identify which tap gesture recognizer is called?

我有 2 个 UIImageView,名为 "artistImage" 和 "albumImage",每个包含 1 个点击手势,所有手势都连接到 1 个@IBAction,名为 "artistImageTap"。这些点击手势是从对象库中拖动并放置在我的 ImageView 上。

故事板 - 代码

我的应用程序有艺术家、专辑和歌曲列表,当点击一首歌曲时,应用程序会移至此视图并显示其详细信息。如果我单击添加按钮,应用程序将移动到此视图,但这次所有文本字段都是可编辑的,图像是默认的,用户可以点击它们以从库中选择 select 图像来创建新歌曲。

我的问题是我不知道如何识别哪个 UIImageView 被点击了。正如你在图片中看到的,我尝试了 picker.restorationIdentifier 但它总是 returns nil。

@IBAction func artistImageTap(_ sender: UITapGestureRecognizer) {
    let imagePickerController = UIImagePickerController()

    // Only allow photos to be picked, not taken.
    imagePickerController.sourceType = .photoLibrary
    // Make sure ViewController is notified when the user picks an image.
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    // The info dictionary may contain multiple representations of the image. You want to use the original.
    guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }

    // Set photoImageView to display the selected image.
    if picker.restorationIdentifier == "artistImage" {
        artistImage.image = selectedImage
    } else {
        albumImage.image = selectedImage
    }
    // Dismiss the picker.
    dismiss(animated: true, completion: nil)
}

不胜感激!!

  • 从情节提要中向两个 UIImageView 添加标签。 像 artistImage = 1001 和 albumImage = 1002

    @IBAction func artistImageTap(_ sender: UITapGestureRecognizer) {
    
    if sender.view?.tag == 1001 {
    
        selectedTag = 1001
    
    } else if sender.view?.tag == 1002 {
    
       selectedTag = 1002
    
    }
    
    let imagePickerController = UIImagePickerController()
    
    // Only allow photos to be picked, not taken.
    imagePickerController.sourceType = .photoLibrary
    // Make sure ViewController is notified when the user picks an image.
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)
    } 
    
  • 将所选标签存储在一个变量中。

  • 现在您可以使用 selectedTag 变量

  • 检查用户在图像上点击了哪个

首先在图像上应用点击手势时设置标签。

tapGestureArtistImage.tag = 0;
tapGestureAlbumImage.tag = 1;

然后在artistImageTap方法

中将点击手势作为参数发送
- (void) artistImageTap:(UITapGestureRecognizer*)sender
{
  if(sender.tag == 0)
  {
    // artistImage tapped
  }
  else if (sender.tag == 1)
  {
    // albumImage tapped
  }
}