Hi, I have a problem with the following code:
When I print out the inputImage, it says it is nil. Why is it like this? Can you help me please?
Code Block Swift struct AddView: View { @State var text:String = "" @State private var image1 : String? @State private var showingPicker = false @Binding var listItems: [Item] @State private var inputImage : String? var body: some View { VStack{ TextField("Name", text: $text).padding().background(Color(.systemGray5)).frame(width: 400,alignment: .center).cornerRadius(20) Image(systemName: "person.circle") .frame(width: 170, height: 170, alignment: .center) .clipShape(Circle()) .shadow(radius: 10) .overlay(Circle() .stroke(Color.blue)) .position(x: 209, y: 100) .onTapGesture { self.showingPicker = true }.sheet(isPresented: $showingPicker, onDismiss: loadImage){ ImagePicker(image: self.$inputImage) } Button(action: { listItems.append(Item(name: text, image: "Gif")) UserDefaults.standard.saveItems(listItems) print(listItems) }, label: { Text("Add") }) } } func loadImage(){ guard let inputImage1 = inputImage else { print(inputImage) return } } } extension UserDefaults { func saveItems(_ items: [Item]) { let encoder = JSONEncoder() if let data = try? encoder.encode(items) { set(data, forKey: "Items") } } } 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 : String]){ if let uiImage = info[.originalImage]{ parent.image = uiImage } parent.presentaitionMode.wrappedValue.dismiss() } } @Environment(\.presentationMode) var presentaitionMode @Binding var image : String? func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController{ let picker = UIImagePickerController() picker.delegate = context.coordinator return picker } func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) { } }
When I print out the inputImage, it says it is nil. Why is it like this? Can you help me please?