【发布时间】:2021-02-24 06:15:45
【问题描述】:
我注意到在 SwiftUI 中使用 NavigationLinks 时,目标视图在呈现之前就已加载,这会导致我的应用程序出现问题。
我使用答案here 来解决这个问题,创建一个 NavigationLazyView 如下:
struct NavigationLazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
self.build = build
}
var body: Content {
build()
}
}
在我的观点中我是这样使用它的:
struct ViewA: View {
var body: some View {
NavigationLink(destination: NavigationLazyView(ViewB())){
Text(text: "Click me")
}
}
}
我尝试更进一步,创建一个惰性版本的导航链接:
struct NavigationLazyLink<Content1 : View, Content2 : View> : View {
let destination : () -> Content1;
let viewBuilder : () -> Content2;
var body: some View {
NavigationLink(destination: NavigationLazyView(destination())){
viewBuilder()
}
}
}
但是,当我尝试像这样使用 NavigationLazyLink 时:
struct ViewA: View {
var body: some View {
NavigationLazyLink(destination: ViewB()){
Text(text: "Click me")
}
}
}
我收到以下错误:
Cannot convert value of type 'ViewB' to expected argument type '() -> Content1'Generic parameter 'Content1' could not be inferredExplicitly specify the generic arguments to fix this issue
我无法完全解决这个问题,我感觉我误解了如何使用泛型类型
【问题讨论】:
标签: swift generics swiftui navigation lazy-loading