如何从 imagePickerController 中 return 一张图片?

How to return an image out of imagePickerController?

我是编程新手,Swift 我找不到问题的解决方案 :

我有 4 个 UIImageView,每个图像顶部都有一个 UIButton。 当我点击一个 UIButton 时,我想打开一个 UIImagePickerController,select 一个图像并将它放在关联的 UIImageView 中(这是我的 Interface Builder 的屏幕)

我已将我的 UIImageView 放入 outlet 集合中

@IBOutlet var layout1Images: [UIImageView]!

这是我的 IBAction 链接到我的 4 个按钮:

@IBAction func openImagePicker(_ sender: UIButton) {
    for image in layout1Images {
        if sender.tag == image.tag {
            
            let picker = UIImagePickerController()
            picker.allowsEditing = true
            picker.delegate = self
            present(picker, animated: true)
            
        }
    }
}

还有我的 imagePickerController:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    guard let image = info[.editedImage] as? UIImage else { return }
    
    //How to return the image to the selected UIImageView ?
            
    dismiss(animated: true)
}

我怎样才能 return 图像到 selected UIImageView ?

感谢您的帮助

首先,将您从 UIButton 获取的标签存储在一个变量中,例如

var selectedTag = 0

openImagePicker() 操作中添加以下行

selectedTag = sender.tag

现在 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])

添加这一行

layoutImages[selectedTag].image = image
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
       guard let image = info[.originalImage] as? UIImage else {
                  fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
              }
// make use of the image
   }