Skip to content

maheenkhalid/SwiftUIBridging

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SwiftUIBridging

This project demonstrates how to integrate UIKit components inside a SwiftUI app using UIViewControllerRepresentable.

We use UIImagePickerController as a real-world example to allow users to pick an image from their photo library.


📸 Features

  • SwiftUI-based layout
  • UIKit interoperability using UIViewControllerRepresentable
  • Image picker wrapped as a reusable SwiftUI component
  • Reactive data flow using @Binding

🧱 Code Overview

ImagePicker.swift

import SwiftUI
import UIKit

struct ImagePicker: UIViewControllerRepresentable {
    @Environment(\.presentationMode) var presentationMode
    @Binding var selectedImage: UIImage?
    var sourceType: UIImagePickerController.SourceType = .photoLibrary

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.sourceType = sourceType
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}

    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 image = info[.originalImage] as? UIImage {
                parent.selectedImage = image
            }
            parent.presentationMode.wrappedValue.dismiss()
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
}

About

Example code to use UIKit Code in SwitUI

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages