在 SwiftUI 中创建惰性 NavigationLink 时出现泛型问题
Posted
技术标签:
【中文标题】在 SwiftUI 中创建惰性 NavigationLink 时出现泛型问题【英文标题】:A generics problem whilst creating a lazy NavigationLink in SwiftUI 【发布时间】:2021-02-24 06:15:45 【问题描述】:我注意到在 SwiftUI 中使用 NavigationLink
s 时,目标视图在呈现之前就已加载,这会导致我的应用程序出现问题。
我使用答案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 inferred
Explicitly specify the generic arguments to fix this issue
我无法完全解决这个问题,我感觉我误解了如何使用泛型类型
【问题讨论】:
【参考方案1】:这是因为destination
是一个闭包:
let destination : () -> Content1
所以你需要将ViewB
作为闭包传递:
NavigationLazyLink(destination: ViewB() )
Text("Click me")
【讨论】:
以上是关于在 SwiftUI 中创建惰性 NavigationLink 时出现泛型问题的主要内容,如果未能解决你的问题,请参考以下文章