【发布时间】:2020-07-05 19:45:15
【问题描述】:
我目前正在开发适用于 iOS / macOS 的照片应用程序,我正在努力使用 PhotoKit。
我确实创建了一个类来管理我的所有 PhotoKit 请求。
class PhotosAPI: ObservableObject {
@Published var all = PHFetchResult<PHAsset>()
@Published var allAlbums = PHFetchResult<PHAssetCollection>()
@Published var allSmartAlbums = PHFetchResult<PHAssetCollection>()
// Functions to get the Collections / Assets
}
到目前为止,这部分工作正常,但现在我正在努力在我的视图中显示这些数据。
在我看来,我想在列表/网格中显示所有资产
struct ShowImages: View {
@ObservedObject var photos = PhotosAPI()
var body: some View {
List(photos.all, id: \.self) { item in
Text("\(item)")
}
}
}
但我确实收到一个错误“初始化程序'init(_:id:rowContent:)' 要求'PHFetchResult' 符合'RandomAccessCollection'”,我今天确实尝试了一整天来解决这个问题,但我没有成功并且我在 google 中找不到任何有用的东西。
有人知道我如何让 PHFetchResults 遍历它们吗?
最后我能够用下面的代码显示图片。但这对我来说似乎是非常糟糕的代码。我宁愿直接在 PHFetchResult 上循环。有谁知道我怎样才能做到这一点?
ForEach(0..<photos.all.count) { index in
Text("\(photos.all.object(at: index).localIdentifier)")
}
【问题讨论】:
-
您可以尝试使
PHFetchResult符合RandomAccessCollection或存储PHAsset的数组而不是PHFetchResults。如果您遇到性能问题,可以使用 iOS 14 中的一种新惰性视图或对照片进行分页。
标签: swift xcode swiftui photokit