ViewModifiers: Image Picker

An easy way to let users select images

Here is some sample code that let you easily present a confirmation dialog that allows users to select a picture from their gallery or take a picture with their camera.

Table Of Contents:

Demo

Note that given the video is recorded in the Canvas’ Preview, the Camera option is not available.

ImageSelectorOptionsModifier

Image Picker

Usage

@State private var isPresentingImagePickerOptions = false
@State private var selectedImage: UIImage?

// ...

someView
    .imageSelectorOptions(
        isPresentingSourceSelector: $isPresentingImagePickerOptions,
        selectedImage: $selectedImage
    )

Demo Code

import SwiftUI

struct ContentView: View {
    @State private var isPresentingImagePickerOptions = false
    @State private var selectedImage: UIImage?

    var body: some View {
        VStack {
            if let selectedImage {
                Image(uiImage: selectedImage)
                    .resizable()
                    .frame(width: 100, height: 100)
                    .clipShape(Circle())

                Button("Clear Selection") {
                    withAnimation {
                        self.selectedImage = nil
                    }
                }
                .tint(.red)
            }
            Button("Present Picker") {
                isPresentingImagePickerOptions = true
            }
            .imageSelectorOptions(
                title: "Select Source",
                titleVisibility: .visible,
                isPresentingSourceSelector: $isPresentingImagePickerOptions,
                selectedImage: $selectedImage
            )
        }
        .padding()
        .buttonStyle(.bordered)
    }
}

#Preview {
    ContentView()
}

Related Articles

ViewModifiers: Image Picker | manu.show
Tags: iOS
Share: X (Twitter) LinkedIn