一、启用相册[picker.sourceType = .photoLibrary]
//检测相册访问权限
//info.plist里开启Photo、Camera的权限
if indexPath.row == 0 {
guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else { return }
//实例化一个UIImagePickerController对象
//属性是:不允许编辑,来源为相册,以模态视图弹出
let picker = UIImagePickerController()
picker.allowsEditing = false
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
}
二、启用摄像头[picker.sourceType = .camera]
//检测相册访问权限
//info.plist里开启Photo、Camera的权限
if indexPath.row == 0 {
guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else { return }
//实例化一个UIImagePickerController对象
//属性是:不允许编辑,来源为相册,以模态视图弹出
let picker = UIImagePickerController()
picker.allowsEditing = false
picker.sourceType = .camera
self.present(picker, animated: true, completion: nil)
}
三、获取相册中的图片
3.1、之前只是能够访问,如果要获取图片[与相册互动],需要遵守两个协议<UIImagePickerControllerDelegate
、UINavigationControllerDelegate
>
3.2、当用户从相册选择一张图后,会触发如下方法,实现该方法,可从方法的参数中取回图片
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//从info字典中,查询"原始图像"
coverImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
//平铺、裁边
coverImageView.contentMode = .scaleAspectFill
coverImageView.clipsToBounds = true
//视图自退场
dismiss(animated: true, completion: nil)
}
四、补充
别忘了设置代理哟,只有设置了代理,才可实现代理的方法
picker.delegate = self
网友评论