【问题标题】:SwiftUI MacOSX ImagePickerSwiftUI MacOSX ImagePicker
【发布时间】:2020-02-24 09:11:38
【问题描述】:

我正在使用 SwiftUI 创建一个 Mac OSX 应用程序。我想要一个 ImagePicker/文件选择器(仅限图像类型)来从文件系统中选择一个图像并将其显示在我的 Image() 中。

我找不到正确的方法。我习惯于在 iOS 中使用 ObjectiveC 的 UIImagePicker。正确的做法是什么?

举个例子,我有一个按钮,想在按下按钮时调用 ImagePicker。

Apple 通讯录正在使用这种模式视图。我们也可以使用吗?

【问题讨论】:

    标签: swift xcode image swiftui


    【解决方案1】:

    macOS 中的 SwiftUI

    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)
    
                        }
                    }
            }
        }
    }
    

    【讨论】:

    • 适用于大多数用途的漂亮而简单的示例。
    【解决方案2】:

    像这样初始化面板:

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

    要添加您想要的选择框,您需要添加以下内容:

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

    您可以使用

    选择您选择的数据类型
    myFiledialog.allowedFileTypes = [“png”, “jpg”, “jpeg”]
    

    要禁用多选添加这个。

    myFiledialog.allowsMultipleSelection = false
    

    我希望这对你有所帮助。

    【讨论】:

    • 谢谢 :) NSOpenPanel 按要求工作。而且 allowedFileTypes 是完美的
    【解决方案3】:

    我为此使用了 Quarz 的 IKPictureTaker。

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

    【讨论】:

    • 谢谢!!这正是我正在寻找的对话!
    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 2019-10-24
    • 2020-10-31
    • 2021-10-16
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多