Swift 打开图库

Swift 打开图库,第1张

概述Swift版本: 3.0 代码 首先在info.plist内添加两个参数如下, 给足权限,否则无法打开图库 Key : Privacy - Media Library Usage DescriptionValue : YES [ It is not boolean, it is String ]Key : Privacy - Photo Library Usage Description

Swift版本: 3.0

代码

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

Key : Privacy - Media library Usage DescriptionValue : YES  [ It is not boolean,it is String ]Key : Privacy - Photo library Usage DescriptionValue : YES [ It is not boolean,it is String ]

在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 打开图库全部内容,希望文章能够帮你解决Swift 打开图库所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1071849.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存