【问题标题】:A generics problem whilst creating a lazy NavigationLink in SwiftUI在 SwiftUI 中创建惰性 NavigationLink 时出现泛型问题
【发布时间】: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 '() -&gt; Content1'
  • Generic parameter 'Content1' could not be inferred
  • Explicitly specify the generic arguments to fix this issue

我无法完全解决这个问题,我感觉我误解了如何使用泛型类型

【问题讨论】:

    标签: swift generics swiftui navigation lazy-loading


    【解决方案1】:

    这是因为destination 是一个闭包:

    let destination : () -> Content1
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-18
      • 2022-01-07
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      相关资源
      最近更新 更多