需求:點(diǎn)擊按鈕,彈出ActionSheet提示框,可選擇從相冊(cè)中選取圖片或者拍照,選擇成功后的照片顯示在按鈕上
1 按鈕的點(diǎn)擊事件
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: "相冊(cè)", 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 打開相機(jī)方法
//打開相機(jī)
func openCamera()
{
//判斷設(shè)置是否支持圖片庫(kù)
if UIImagePickerController.isSourceTypeAvailable(.camera){
//初始化圖片控制器
let picker = UIImagePickerController()
//設(shè)置代理
picker.delegate = self
//指定圖片控制器類型
picker.sourceType = UIImagePickerControllerSourceType.camera
//彈出控制器,顯示界面
self.present(picker, animated: true, completion: {
() -> Void in
})
}else{
print("讀取相機(jī)錯(cuò)誤")
}
}
4 打開相冊(cè)方法
func takePhoto()
{
//判斷設(shè)置是否支持圖片庫(kù)
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
//初始化圖片控制器
let picker = UIImagePickerController()
//設(shè)置代理
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("讀取相冊(cè)錯(cuò)誤")
}
}
6 選擇相冊(cè)成功的代理方法
// 選擇圖片成功后代理
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(info)
// 得到 UIImage 類型的照片
btnImage = info[UIImagePickerControllerOriginalImage]as!UIImage
// 照片顯示在按鈕上(當(dāng)在代理方法中無法傳值的時(shí)候,設(shè)置全局變量,進(jìn)行傳值)
self.currentBtn.setBackgroundImage(btnImage, for: .normal)
picker.dismiss(animated:true, completion:nil)
}