升级到 Swift 6 后,我的照片应用程序出现问题。在下面的示例中,我收到此错误(无法从 Sendable 闭包引用主要参与者隔离属性“photoImage”)。有谁知道如何解决这个问题?在启动时将其分配给 .task 中的不同值也不起作用。
import SwiftUI
import PhotosUI
@Observable
final class CameraModel {
var thumbnail: String?
}
struct ContentView: View {
@State var camera = CameraModel()
@State var selectedItems: [PhotosPickerItem] = []
var body: some View {
PhotosPicker(selection: $selectedItems, photoLibrary: .shared()) {
// I’m getting an error here
photoImage
}
}
@ViewBuilder
private var photoImage: some View {
if let thumbnail = camera.thumbnail {
Image(thumbnail)
.resizable()
.aspectRatio(contentMode: .fill)
.animation(.easeInOut(duration: 0.3), value: thumbnail)
} else {
Image(systemName: "photo.on.rectangle")
}
}
}
#Preview {
ContentView(camera: CameraModel())
}
只需将您的
photoImage
标记为 nonisolated
struct ContentView: View {
//@State var camera = CameraModel()
@State var selectedItems: [PhotosPickerItem] = []
var body: some View {
PhotosPicker(selection: $selectedItems, photoLibrary: .shared(), label: {
photoImage
})
}
@ViewBuilder
nonisolated private var photoImage: some View { //<- mark here
...
}
}