Home > AI > IOS > SwiftUI >

UIImagePickerController

ImagePickerView.swift

struct ImagePickerView: UIViewControllerRepresentable {
    
    @Environment(\.presentationMode) var mode
    @Binding var image: Image?
    
    typealias UIViewControllerType = UIImagePickerController
    

    
    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        @Binding var mode: PresentationMode
        @Binding var image: Image?
        
        init(mode: Binding<PresentationMode>, image: Binding<Image?>) {
            _mode = mode
            _image = image
        }
        
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
            image = Image(uiImage: uiImage)
            mode.dismiss()
        }
        
        
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            mode.dismiss()
        }
    }
    
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(mode: mode, image: $image)
        
    }
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
    }
}

ContentView.swift

struct ContentView: View {
    
    @State var isPresented: Bool = false
    @State var image: Image? = Image(systemName: "pencil")
    
    var body: some View {
        NavigationView {
            ZStack {
                VStack {
                    image?
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(height:300)
                    
                    Button(action: {
                        self.isPresented.toggle()
                    }, label: {
                        Image(systemName: "photo")
                        Text("Input photo")
                            .font(.headline)
                    })
                    Spacer()
                }
            }.sheet(isPresented: $isPresented, content: {
                ImagePickerView(image: $image)
            })
            .navigationTitle("Apple photo")
        }
    }
}

Leave a Reply