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

时间:2018-01-15 09:50:39

标签: ios swift xcode uiimageview uitapgesturerecognizer

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

故事板 - 代码 enter image description here

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

我的问题是我不知道如何识别哪个UIImageView被点击。正如你在图片中看到的那样,我尝试了picker.restorationIdentifier,但它总是返回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)
}

感谢每一位帮助!!

2 个答案:

答案 0 :(得分:1)

  • 从故事板向两个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变量点击的图片用户

答案 1 :(得分:0)

首先,当您将图像应用于图像时,为手势设置标记。

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

然后在artistImageTap方法

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