繁体   English   中英

在 SwiftUI 中创建惰性 NavigationLink 时出现泛型问题

[英]A generics problem whilst creating a lazy NavigationLink in SwiftUI

我注意到在 SwiftUI 中使用NavigationLink时,目标视图在显示之前加载,这会导致我的应用程序出现问题。

我使用这里的答案来解决这个问题,创建一个 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 inferred
  • Explicitly specify the generic arguments to fix this issue

我不能完全解决这个问题,我有一种感觉,我误解了如何使用泛型类型

这是因为destination是一个闭包:

let destination : () -> Content1

所以你需要将ViewB作为闭包传递:

NavigationLazyLink(destination: { ViewB() }) {
    Text("Click me")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM