使用UIImagePickerController从相册选择照片

Swift 4

  1. 在info.plist添加
    NSPhotoLibraryUsageDescription
    This app requires access to the photo library.
  2. View Controller需要implement UIImagePickerControllerDelegate, UINavigationControllerDelegate这两个delegate
  3. 申明需要的IBOutlet组件和定义UIImagePickerController
  4. 把UIImagePickerController的delegate设为自己的ViewController
  5. 实现imagePickerController方法
import UIKit

// 2.
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    // 3.
    @IBOutlet weak var inputImgBtn: UIButton!
    @IBOutlet weak var imageView: UIImageView!
    var imagePicker = UIImagePickerController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    

    @IBAction func inputImageBtnPress(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            // 4.
            imagePicker.delegate = self
            // get full access, otherwise use .savedPhotosAlbum
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = false
            // Starts up the UIImagePickerController
            present(imagePicker, animated: true, completion: nil)
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        guard let selectedImage = info[.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        imageView.image = selectedImage
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion:nil)
    }
}

你可能感兴趣的:(使用UIImagePickerController从相册选择照片)