美文网首页Swift基础入坑
相册-UIImagePickerController

相册-UIImagePickerController

作者: iOS_July | 来源:发表于2018-06-11 10:41 被阅读21次

    一、启用相册[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、之前只是能够访问,如果要获取图片[与相册互动],需要遵守两个协议<UIImagePickerControllerDelegateUINavigationControllerDelegate>
    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
    

    相关文章

      网友评论

        本文标题:相册-UIImagePickerController

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