通过懒加载来实现从相册或拍照添加图片
1、声明懒加载属性imagePickerController
lazy var imagePickerController: UIImagePickerController = {
let vc = UIImagePickerController.init()
vc.delegate = self
vc.allowsEditing = true
return vc
}()
2、显示相册和拍照选项的SheetView
func showSheetView() -> Void {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// 拍照选项
let takingPicturesAction = UIAlertAction(title:"拍照", style: .default)
{
action in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.imagePickerController.sourceType = .camera;
self.present(self.imagePickerController, animated: true, completion: nil)
} else {
print("当前设备不支持拍照")
}
}
// 相册选项
let photoLibraryAction = UIAlertAction(title:"相册", style: .default)
{
action in
self.imagePickerController.sourceType = .photoLibrary;
self.present(self.imagePickerController, animated: true, completion: nil)
}
// 取消选项
let cancelAction = UIAlertAction(title:"取消", style: .cancel, handler: nil)
alertController.addAction(takingPicturesAction)
alertController.addAction(photoLibraryAction)
alertController.addAction(cancelAction)
self.present(alertController, animated:true, completion:nil)
}
3、获取imagePickerController返回的图片
// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension AddProductController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// 获取照片
let image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
addPictureButton.setImage(image, for: .normal)
addPictureButton.setTitle("", for: .normal)
self.dismiss(animated: true, completion: nil)
}
}
网友评论