Photo library in Swift UI

View your photo library in Swift UI

Tap the button to display your photo library. Select a photo in your photo library to see it in full screen.

environment

Swift 5.3 Xcode 12.0.1 macOS 10.15.7

Photo library

Define a structure that wraps your photo library in Swift UI.

ImagePicker.swift


import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    var sourceType: UIImagePickerController.SourceType = .photoLibrary
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = false
        imagePicker.sourceType = sourceType
        return imagePicker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

    }
}

First screen

This is the basic screen structure of the app. Displays the photo library in sheet format based on state variables.

ContentView.swift


import SwiftUI

struct ContentView: View {
    @State private var image = UIImage()
    @State private var isShowPhotoLibrary = false
    
    var body: some View {
        VStack {
            Image(uiImage: self.image)
            Button(action: {
                self.isShowPhotoLibrary = true
            }, label: {
                Text("Photo Library")
                    .padding()
            })
        }
        .sheet(isPresented: $isShowPhotoLibrary, content: {
            ImagePicker(sourceType: .photoLibrary)
        })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Select a photo in your photo library

ʻConforms to the UIImagePickerControllerDelegate` protocol.

ImagePicker.swift


import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    // MARK: - Working with UIViewControllerRepresentable
    var sourceType: UIImagePickerController.SourceType = .photoLibrary
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = false
        imagePicker.sourceType = sourceType
        imagePicker.delegate = context.coordinator  // Coordinater to adopt UIImagePickerControllerDelegate Protcol.
        return imagePicker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

    }

    // MARK: - Using Coordinator to Adopt the UIImagePickerControllerDelegate Protocol
    @Binding var selectedImage: UIImage
    @Environment(\.presentationMode) private var presentationMode
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        var parent: ImagePicker
        
        init(_ parent: ImagePicker) {
            self.parent = parent
        }
     
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
     
            if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                parent.selectedImage = image
            }
     
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
}

Show selected photo

ʻAdd a modifier to the Image view. Set the selected photo to the ʻimage property at the timing of screen transition.

ContentView.swift


struct ContentView: View {
    @State private var image = UIImage()
    @State private var isShowPhotoLibrary = false
    
    var body: some View {
        VStack {
            Image(uiImage: self.image)
                .resizable()
                .scaledToFill()
                .frame(minWidth: 0, maxWidth: .infinity)
                .edgesIgnoringSafeArea(.all)
            Button(action: {
                self.isShowPhotoLibrary = true
            }, label: {
                Text("Photo Library")
                    .padding()
            })
        }
        .sheet(isPresented: $isShowPhotoLibrary, content: {
            ImagePicker(sourceType: .photoLibrary, selectedImage: self.$image)
        })
    }
}

Recommended Posts

Photo library in Swift UI
Create Master Detail in Swift UI
Implementing side menus in Swift UI
Swift UI 100 knocks
Customize View with View Modifier in Swift UI
SKStoreReviewController implementation memo in Swift UI of iOS14
Compare objects in Swift
Swift UI TextView placeholder
Division becomes 0 in Swift
Starting with Swift Swift UI
Multidimensional array in Swift
List of devices that can be previewed in Swift UI
Implement Swift UITextField in code
[Swift UI] Use Map view
How to change BackgroundColor etc. of NavigationBar in Swift UI
Make an FPS counter in Swift
Automatic photo resizing method in Java
[React Native] Write Native Module in Swift
Specify multiple sort conditions in Swift
Handle C char ** well in Swift
[Swift 5] Implement UI for review function
Time stamps in nanoseconds even in Swift!
Try to display a slightly rich Webview in Swift UI using UIViewRepresentable