在导航链接内时,SwiftUI onAppear 被多次调用。在我提供的示例中,它被调用了 5 次。这也会触发它的 StateObject 初始值设定项也被调用 5 次。如果您注释掉导航链接,它会按预期执行。
这已经在 Xcode 12 GM 和 Xcode 12.2 以及 iOS 14 GM 和 iOS 14.2 beta 1 上进行了测试。也作为反馈 FB8721761 提交。
struct ContentView: View {
var body: some View {
NavigationLink(destination: Color.red, label: {
ImageView()
.frame(width: 166.66, height: 250)
.cornerRadius(10)
})
}
}
struct ImageView: View{
@StateObject private var downloader = Downloaded(url: URL(string: "https://image.tmdb.org/t/p/w342/TnOeov4w0sTtV2gqICqIxVi74V.jpg")!)
var body: some View{
Rectangle()
.onAppear{
print("Appeared")
}
}
}
class Downloaded: ObservableObject{
var cancellable: AnyCancellable?
let url: URL
init(url: URL){
self.url = url
download()
}
func download(){
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
.sink(receiveCompletion: { _ in
print("Finished downloading")
}, receiveValue: {_ in})
}
}
Run Code Online (Sandbox Code Playgroud)
我向 Apple 提交了反馈,该问题已在 iOS 14.2 beta 3 中得到解决。
| 归档时间: |
|
| 查看次数: |
910 次 |
| 最近记录: |