美文网首页
使用UIImagePickerController从相册选择照片

使用UIImagePickerController从相册选择照片

作者: 黑山老水 | 来源:发表于2020-04-22 15:47 被阅读0次

    Swift 4

    1. 在info.plist添加
      <key>NSPhotoLibraryUsageDescription</key>
      <string>This app requires access to the photo library.</string>
    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从相册选择照片

          本文链接:https://www.haomeiwen.com/subject/pywiihtx.html