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

标签 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
            }
        }
    }

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

我尝试过:

matching: [.images, .videos],

并得到:

Cannot convert value of type '[Any]' to expected argument type 'PHPickerFilter?'

最佳答案

解决方案

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

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

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

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

示例

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

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

结果

<表类=“s-表”> <标题> 模拟器库 应用中 PhotoPicker 的变体 <正文> enter image description here enter image description here

您可以在 View here 上找到 Apple 文档。

关于iOS SwiftUI - 使用 PhotosPicker 从图库中选择图像或视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73961615/

相关文章:

ios - Apple 在导航堆栈中使用的后退按钮图形在哪里?

ios - swiftUI 转换 : Scale from some frame - like iOS Homescreen is doing when opening an App

swift - 在其他数组中使用 ForEach 的索引

objective-c - 如何设置部分 curl 模式不隐藏工具栏?

ios - 使用自定义按钮重新排序 tableview 单元格

ios - UISlider值将 float 转换为百分比

swift - 使用 Combine 框架的按钮操作

ios - 如何一次更改核心数据中所有实体的属性值?

ios - RxSwift - 按下按钮时显示/隐藏警告标签

ios - 我如何模仿 map 应用程序的底部工作表?