在 SwiftUI 中创建惰性 NavigationLink 时的遗传问题
A generics problem whilst creating a lazy NavigationLink in SwiftUI
我注意到在 SwiftUI 中使用 NavigationLink
s 时,目标视图在显示之前加载,这导致我的应用程序出现问题。
我使用答案 解决了创建 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")
}
}
}
我尝试更进一步,创建一个惰性版本的导航 link:
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")
}
我注意到在 SwiftUI 中使用 NavigationLink
s 时,目标视图在显示之前加载,这导致我的应用程序出现问题。
我使用答案
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")
}
}
}
我尝试更进一步,创建一个惰性版本的导航 link:
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")
}