Swift 打开图库

前端之家收集整理的这篇文章主要介绍了Swift 打开图库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Swift版本: 3.0

代码

  1. 首先在info.plist内添加两个参数如下,给足权限,否则无法打开图库

    Key : Privacy - Media Library Usage Description
    Value : YES  [ It is not boolean,it is String ]
    
    Key : Privacy - Photo Library Usage Description
    Value : YES [ It is not boolean,it is String ]
  2. 在ViewController中改为如下代码

    import UIKit
    // 首先在头部加入当前Controller需要遵从的代理
    class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 创建一个对象
    // 这个对象是用来在屏幕上显示
    @IBOutlet weak var imagePicked: UIImageView!
    // 这个Action方法对应着屏幕上的按钮,该按钮点击后会调用图库
    @IBAction func add(_ sender: UIBarButtonItem) {
    // 判断数据源是否合法,这里的.photoLibrary省略了其类名,Swift会自动推导
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = true
            // 这一句,开始调用图库
            self.present(imagePicker,animated: true)
        }
    }
    // 实现代理的方法
    // 注意,这里和swift3.0之前的版本实现方法都不太一样,这是唯一的写法,网上流传的其他方法都是过时的
    
    func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
        // 将图片显示给UIImageView
            imagePicked.image = image
        }else{
            print("pick image wrong")
        }
        // 收回图库选择界面
        self.dismiss(animated: true,completion: nil)
    }
    }

实际效果


打开图库


显示到界面

参考:
http://stackoverflow.com/questions/37925583/uiimagepickercontroller-crashes-app-swift3-xcode8

http://stackoverflow.com/questions/39009889/xcode-8-creating-an-image-format-with-an-unknown-type-is-an-error


完整demo百度云下载链接

猜你在找的Swift相关文章