iOS SwiftUI - 使用 PhotosPicker 从图库中选择图像或视频

IHa*_*gle 3 ios swift swiftui

我正在尝试使用新的 PhotosPicker:

PhotosPicker(
    selection: $selectedItem,
    matching: .videos,
    photoLibrary: .shared()) {
        Text("Select a photo")
    }
    .onChange(of: selectedItem) { newItem in
        Task {
            if let data = try? await newItem?.loadTransferable(type: Data.self) {
                selectedImageData = data
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我如何设置选择图像或视频而不是仅选择其中之一?

我试过:

matching: [.images, .videos],
Run Code Online (Sandbox Code Playgroud)

并得到:

Cannot convert value of type '[Any]' to expected argument type 'PHPickerFilter?'
Run Code Online (Sandbox Code Playgroud)

Vis*_*kse 5

解决方案

注意到matching参数的类型为PHPickerFilter,您可以使用.any(of:)静态函数来组合过滤器。例如:

PhotosPicker("Pick Photo",
             selection: $item,
             matching: .any(of: [.images, .videos])) // <- combine filters
Run Code Online (Sandbox Code Playgroud)

或者假设您想排除“类型”过滤器

PhotosPicker("Pick Photo",
             selection: $item,
             matching: .any(of: [.images, .not(.videos)])) //<- Use the .not() to exclude filters
Run Code Online (Sandbox Code Playgroud)

例子

让我们看一下我写的示例代码:

// Other views...
VStack {
            // Pick either photos or videos
            PhotosPicker("Pick **EITHER** Photos or Videos", //<- Bonus tip: You can use markdowns in swift
                         selection: $item,
                         matching: .any(of: [.images, .videos]))
            
            // Filter out photos with the .not() function
            PhotosPicker("Pick **ONLY** Videos",
                         selection: $item,
                         matching: .any(of: [.videos, .not(.images)]))
        }
Run Code Online (Sandbox Code Playgroud)

结果

模拟器画廊 应用程序中 PhotoPicker 的变体
在此输入图像描述 在此输入图像描述

您可以在此处查看 Apple 文档