如何为照片库制作 UIImagePickerController 和我的问题

How to make UIImagePickerController for photo library and my problem

我使用 UIImagePickerController,我希望我的应用程序允许我 select 来自照片库的照片。
我有一个界面屏幕:

我有图像视图,我希望在单击图像视图时打开图库。接下来,我select编辑了一张图片,它被插入到这个圈子中。

我select照片库中的一张图片后,我的图片没有显示在圈子中。请帮助我:(

我的代码:

import UIKit

class ProfileSettingsViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

  @IBOutlet weak var cancelButton: UIButton!
  @IBOutlet weak var uploadNewPhoto: UIImageView!


  override func viewDidLoad() {
    super.viewDidLoad()
    //    installCancelButtonColor()
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ProfileSettingsViewController.imageTapped(gesture:)))
    uploadNewPhoto.addGestureRecognizer(tapGesture)
    uploadNewPhoto.isUserInteractionEnabled = true
  }

  @objc func imageTapped(gesture: UIGestureRecognizer) {
    // if the tapped view is a UIImageView then set it to imageview
    if (gesture.view as? UIImageView) != nil {
      print("Image Tapped")
      let imageC = UIImagePickerController()
      imageC.delegate = self
      imageC.sourceType = UIImagePickerController.SourceType.photoLibrary
      present(imageC, animated: true)

    }
  }

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
      picker.dismiss(animated: true)

      guard let image = info[.editedImage] as? UIImage else {
          print("No image found")
          return
      }

      // print out the image size as a test
      print(image.size)
  }

  //  func installCancelButtonColor() {
  //    cancelButton.layer.borderWidth = 1.5
  //    let cancelButtonColor = UIColor(red: 0.20, green: 0.28, blue: 0.36, alpha: 1)
  //    cancelButton.layer.borderColor = cancelButtonColor.cgColor
  //  }


  @IBAction func cancelButton(_ sender: Any) {
    dismiss(animated: true, completion: nil)
  }
}

要在 UIImageView 中查看图像,您需要对其进行设置。

 if let image = info[.editedImage] as? UIImage {
     uploadNewPhoto.image = image
 }

如果您没有从 didFinishPickingMediaWithInfo 获取图像,请尝试将 .editedImage 替换为 .originalImage

当你打开 PhotoLibrary 这个

时最好指定
imageC.mediaTypes = ["public.image"] // this will allow the user to see and select photos only