我正在尝试使用新的 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)]))
}
结果
您可以在 View here 上找到 Apple 文档。
关于iOS SwiftUI - 使用 PhotosPicker 从图库中选择图像或视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73961615/