需求:點擊按鈕,彈出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)
}