再以同樣的sourceType
UIImagePickerViewController
的區別,你可以引入一個新的實體Role
:
fileprivate enum ImagePickerRole {
case avatar
case chooseImage
case takePhoto
}
fileprivate class ImagePicker: UIImagePickerController {
private(set) var role: ImagePickerRole = .takePhoto
}
fileprivate extension ImagePicker {
convenience init(role imagePickerRole: ImagePickerRole) {
self.init()
role = imagePickerRole
switch role {
case .avatar, .takePhoto:
sourceType = .camera
cameraCaptureMode = .photo
showsCameraControls = true
case .chooseImage:
sourceType = .photoLibrary
}
}
而且在你UIImagePickerViewControllerDelegate
可以檢查控制器的角色:
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let imagePicker = picker as? ImagePicker else { return }
switch imagePicker.role {
case .avatar:
// Your code here
case .takePhoto:
// Your code here
case .chooseImage:
// Your code here
}
}