Created
March 17, 2023 07:30
-
-
Save pmstani/17ccb9cd5c20171a18e6b466da55f880 to your computer and use it in GitHub Desktop.
Photo picker using fullscreencover in SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import PhotosUI | |
struct ContentView: View { | |
@State var showPhotoPicker = false | |
@State var selectedImage: UIImage? | |
var body: some View { | |
VStack { | |
if let image = selectedImage { | |
Image(uiImage: image) | |
.resizable() | |
.aspectRatio(contentMode: .fit) | |
} else { | |
Text("No Image Selected") | |
} | |
Button("Select Photo") { | |
self.showPhotoPicker = true | |
} | |
.fullScreenCover(isPresented: $showPhotoPicker) { | |
PhotoPicker(selectedImage: self.$selectedImage) | |
} | |
} | |
} | |
} | |
struct PhotoPicker: UIViewControllerRepresentable { | |
@Environment(\.presentationMode) var presentationMode | |
@Binding var selectedImage: UIImage? | |
func makeUIViewController(context: Context) -> PHPickerViewController { | |
var configuration = PHPickerConfiguration() | |
configuration.filter = .images | |
configuration.selectionLimit = 1 | |
let picker = PHPickerViewController(configuration: configuration) | |
picker.delegate = context.coordinator | |
return picker | |
} | |
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {} | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
class Coordinator: PHPickerViewControllerDelegate { | |
let parent: PhotoPicker | |
init(_ parent: PhotoPicker) { | |
self.parent = parent | |
} | |
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { | |
if let image = results.first?.itemProvider.loadObject(ofClass: UIImage.self) as? UIImage { | |
self.parent.selectedImage = image | |
self.parent.presentationMode.wrappedValue.dismiss() | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Re original question: "Is it possible in SwiftUI to display the PhotoPicker using fullScreenCover? #SwiftUI"
Awesome, thank you very much for the example. I had trouble with
func picker(_:,:)
inXcode 14.3 Beta 3
. I corrected using the following version:The rest works great. Cheers!