Skip to content

Instantly share code, notes, and snippets.

@PaulWoodIII
Created August 8, 2019 12:33
Show Gist options
  • Save PaulWoodIII/aefdcd537436090c321864d1c95ed721 to your computer and use it in GitHub Desktop.
Save PaulWoodIII/aefdcd537436090c321864d1c95ed721 to your computer and use it in GitHub Desktop.
display a selected image using UIViewControllerRepresentable and bindings to a selected UIImage to pass information back to SwiftUI
//: [Previous](@previous)
import SwiftUI
import PlaygroundSupport
struct PhotoPickerDisplayer: View {
@State var presentation: Bool = false
@State var selectedImage: UIImage? = nil
var body: some View {
NavigationView{
VStack{
if selectedImage != nil {
Image(uiImage: selectedImage!)
.resizable()
.aspectRatio(nil, contentMode: .fit)
} else {
Text("Tap the top photo button to select an image to display")
.font(.footnote)
.foregroundColor(Color.black.opacity(0.6))
}
}.navigationBarTitle("Photo Selection")
.navigationBarItems(trailing: Button(action: {
self.presentation = true
}) {
Image(systemName: "photo")
}).sheet(isPresented: $presentation, content: {
PhotoPickerModal(isPresented: self.$presentation,
selectedImage: self.$selectedImage)
})
}
}
}
struct PhotoPickerModal: UIViewControllerRepresentable {
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var isPresented: Binding<Bool>
let selectedImage: Binding<UIImage?>
init(isPresented: Binding<Bool>, selectedImage: Binding<UIImage?>) {
self.isPresented = isPresented
self.selectedImage = selectedImage
}
func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
defer {
picker.dismiss(animated: true, completion: nil)
}
if let editedImage = info[.editedImage] as? UIImage {
self.selectedImage.wrappedValue = editedImage
return
} else if let originalImage = info[.originalImage] as? UIImage {
self.selectedImage.wrappedValue = originalImage
return
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
isPresented.wrappedValue = false
}
}
let isPresented: Binding<Bool>
let selectedImage: Binding<UIImage?>
func makeCoordinator() -> PhotoPickerModal.Coordinator {
return Coordinator(isPresented: self.isPresented, selectedImage: self.selectedImage)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<PhotoPickerModal>) -> UIImagePickerController {
print(isPresented)
let vc = UIImagePickerController()
vc.delegate = context.coordinator
return vc
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<PhotoPickerModal>) {
}
}
let viewController = UIHostingController(rootView:
PhotoPickerDisplayer()
)
PlaygroundPage.current.liveView = viewController
//: [Next](@next)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment