I have two different buttons : Camera button and Album button. When tapping on the album button in order to select an image from photo library, the camera opens. Once I opened the camera by tapping in the camera button, the album works correctly.
I don't know what to do. Here is my code :
struct MemeCreator: View {
@State private var sourceType: UIImagePickerController.SourceType = .camera
@State private var image: Image?
@State private var showingImagePicker = false
@State private var inputImage: UIImage?
@Environment(\.presentationMode) var mode: Binding<PresentationMode>
var body: some View {
NavigationView {
Group {
if let image = image {
Rectangle()
.scaledToFill()
.foregroundColor(.gray)
.overlay(
image
.resizable()
.scaledToFit()
)
} else {
Rectangle()
.scaledToFill()
.foregroundColor(Color(red: 0.15, green: 0.15, blue: 0.15))
}
}
.navigationBarTitle(Text(""), displayMode: .inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(
action: {
}
) {
Image(systemName: "square.and.arrow.up")
.font(.title)
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(
action: {
self.mode.wrappedValue.dismiss()
}
) {
Text("Cancel")
}
}
ToolbarItemGroup(placement: .bottomBar) {
Spacer()
Button(
action: {
sourceType = .camera
showingImagePicker = true
}
) {
Image(systemName: "camera.fill")
}
Spacer()
Button(
action: {
sourceType = .photoLibrary
showingImagePicker = true
}
) {
Text("Album")
}
Spacer()
}
}
}
.sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {
ImagePicker(image: $inputImage, sourceType: sourceType)
}
}
Here is the ImagePicker code :
struct ImagePicker: UIViewControllerRepresentable {
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.image = uiImage
}
parent.presentationMode.wrappedValue.dismiss()
}
}
@Environment(\.presentationMode) var presentationMode
@Binding var image: UIImage?
var sourceType: UIImagePickerController.SourceType
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.sourceType = sourceType
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
}