从相册选取图片,显示在按钮上

需求:点击按钮,弹出ActionSheet提示框,可选择从相册中选取图片或者拍照,选择成功后的照片显示在按钮上

1 按钮的点击事件

 func topPictureBtnClick(){
     self.choosePictureAlert()
 }

2 弹出提示框

 func choosePictureAlert(){
        var alert: UIAlertController!
        alert = UIAlertController(title: "\(alertTitle!)", message: "", preferredStyle: UIAlertControllerStyle.actionSheet)
        let cleanAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler:nil)
        let photoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.openCamera()
        }
        let choseAction = UIAlertAction(title: "相册", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.takePhoto()
        }
        alert.addAction(cleanAction)
        alert.addAction(photoAction)
        alert.addAction(choseAction)
        DispatchQueue.main.async {
            self.present(alert, animated: true, completion: nil)
        }
   } 

3 打开相机方法

    //打开相机
    func openCamera()
    {
        //判断设置是否支持图片库
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //初始化图片控制器
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.camera
            //弹出控制器,显示界面
            self.present(picker, animated: true, completion: {
                () -> Void in
            })
        }else{
            print("读取相机错误")
        }
    }

4 打开相册方法

    func takePhoto()
    {
        //判断设置是否支持图片库
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            //初始化图片控制器
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            //picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
            picker.videoMaximumDuration = 10
            //弹出控制器,显示界面
            self.present(picker, animated: true, completion: {
                () -> Void in
            })
        } else {
            print("读取相册错误")
        }
    }

6 选择相册成功的代理方法

   // 选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
       // 得到 UIImage 类型的照片 
        btnImage = info[UIImagePickerControllerOriginalImage]as!UIImage
       // 照片显示在按钮上(当在代理方法中无法传值的时候,设置全局变量,进行传值)
        self.currentBtn.setBackgroundImage(btnImage, for: .normal)
        picker.dismiss(animated:true, completion:nil)
    }

你可能感兴趣的:(从相册选取图片,显示在按钮上)