首页 > 解决方案 > 无法在同一视图控制器上触发 2 个图像的点击手势标识符

问题描述

我在我的视图控制器中为我的 2 个图像分配了 2 个不同的点击手势标识符。我想在点击时访问并分配不同的图像。我编写了以下代码,它仅适用于一个图像。但是,我不确定如何将它分配给两个不同的图像。我什至为这两个图像分配了不同的标签,但不知道如何使用它们。任何帮助将不胜感激!谢谢!

import UIKit

class EleventhViewController: UIViewController { 

@IBOutlet weak var person1ImageView: UIImageView!

@IBOutlet weak var person2ImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    person1ImageView.tag = 1
    person2ImageView.tag = 2

}

extension EleventhViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

//This is the tap gesture added on my UIImageView.

@IBAction func didTapOnImageView(sender: UITapGestureRecognizer) {
    //call Alert function
    self.showAlert()
}

//Show alert to selected the media source type.
private func showAlert() {

    let alert = UIAlertController(title: "Image Selection", message: "From where you want to pick this image?", preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action: UIAlertAction) in
        self.getImage(fromSourceType: .camera)
    }))
    alert.addAction(UIAlertAction(title: "Photo Album", style: .default, handler: {(action: UIAlertAction) in
        self.getImage(fromSourceType: .photoLibrary)
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

//get image from source type
private func getImage(fromSourceType sourceType: UIImagePickerController.SourceType) {

    //Check is source type available
    if UIImagePickerController.isSourceTypeAvailable(sourceType) {

        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.sourceType = sourceType
        self.present(imagePickerController, animated: true, completion: nil)
    }
}

//MARK:- UIImagePickerViewDelegate.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    self.dismiss(animated: true) { [weak self] in

        guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
        //Setting image to your image view
        
        self?.person2ImageView.image = image
    }
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}

}

标签: iosswiftxcode

解决方案


您必须UITapGestureRecognizer为每个 imageView 创建一个对象并添加它,如果您将相同的 1 添加到两个图像,它将仅触发最后一个 1

 var last = 0
 @objc func didTapOnImageView(sender: UITapGestureRecognizer) { 
    last = sender.view!.tag
 }
 

推荐阅读