I'm trying to make the user select photos (max of 3) to display for my dating app, similar to tinder. The problem occurs after selecting one image, which gets displayed on the three add buttons displays instead of only one.
@State private var personImage: UIImage?
@State private var isShowingPhotoPicker = false
var body: some View {
VStack {
HStack {
ForEach(0..<3) { personImage in
Button {
isShowingPhotoPicker.toggle()
} label: {
if let personImage = self.personImage
Image(uiImage: personImage)
.resizable()
} else {
Image(systemName: "plus.app.fill")
.font(.system(size: 64))
}
}
}
}
}
}
.fullScreenCover(isPresented: $isShowingPhotoPicker, onDismiss: nil) {
PhotoPicker(personImage: $personImage)
}
Here is the PhotoPicker()
:
struct PhotoPicker: UIViewControllerRepresentable {
@Binding var personImage: UIImage?
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.allowsEditing = true
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { }
func makeCoordinator() -> Coordinator {
return Coordinator(photoPicker: self)
}
final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let photoPicker: PhotoPicker
init(photoPicker: PhotoPicker) {
self.photoPicker = photoPicker
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.editedImage] as? UIImage {
guard let data = image.jpegData(compressionQuality: 0.2), let compressedImage = UIImage(data: data) else {
// return an error show an alert
return
}
photoPicker.personImage = compressedImage
} else {
// return an error show an alert
}
picker.dismiss(animated: true)
}
}
}
CodePudding user response:
This other question on Stack fixed the issue! Just had to make a couple of tweaks on the PhotoPicker
and add an enum
.
Definitely would recommend adding this great resource to Bookmarks to help you get past this error in the future.
How do I make two separate calls to an Imagepicker in SwiftUI?