SwiftUI MacOSX ImagePicker

Viewed 1924

I am creating a Mac OSX app with SwiftUI. I want to have a ImagePicker/ File Picker (only Image types) to select a Image from the File System and to display it in my Image().

I couldn't find the correct way of doing it. I am used to UIImagePicker in iOS with ObjectiveC. What is the correct way of doing it?

Just to give you a example, I have a button and want to call the ImagePicker on Button press.

enter image description here

Apple contacts book is using this kind of modal view. Is that available for us too?

3 Answers

SwiftUI in macOS

import SwiftUI

struct FileView: View {
    var body: some View {
        Button("Select File") {
            let openPanel = NSOpenPanel()
            openPanel.prompt = "Select File"
            openPanel.allowsMultipleSelection = false
                openPanel.canChooseDirectories = false
                openPanel.canCreateDirectories = false
                openPanel.canChooseFiles = true
                openPanel.allowedFileTypes = ["png","jpg","jpeg"]
                openPanel.begin { (result) -> Void in
                    if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
                        let selectedPath = openPanel.url!.path
                        print(selectedPath)

                    }
                }
        }
    }
}

initialize the panel like this:

let myFiledialog = NSOpenPanel()
myFiledialog.prompt = “Select path”

to add a selectbox like you want you need to add this:

myFiledialog.worksWhenModal = true
myFiledialog.canChooseDirectories = false
myFiledialog.canChooseFiles = true

you can select the datatype of your choice with

myFiledialog.allowedFileTypes = [“png”, “jpg”, “jpeg”]

to disable the multiselect add this.

myFiledialog.allowsMultipleSelection = false

i hope this helped you.

I used the IKPictureTaker from Quarz for this.

image
    .gesture(
        TapGesture().onEnded{
        let imageChooser: IKPictureTaker = IKPictureTaker.pictureTaker()
        imageChooser.runModal()
        self.image = Image(nsImage: imageChooser.outputImage())
     }
Related