在 SwiftUI 中有条件地使用视图
问题描述:
我正在尝试找出使用 swiftui 有条件地包含视图的正确方法.我无法直接在视图中使用 if
并且不得不使用堆栈视图来做到这一点.
I'm trying to figure out the correct way to conditionally include a view with swiftui. I wasn't able to use the if
directly inside of a view and had to use a
stack view to do it.
这可行,但似乎有更简洁的方法.
This works but there seems like there would be a cleaner way.
var body: some View {
HStack() {
if keychain.get("api-key") != nil {
TabView()
} else {
LoginView()
}
}
}
答
避免使用像 HStack
这样的额外容器的最简单方法是将 body
属性注释为 @ViewBuilder,像这样:
The simplest way to avoid using an extra container like HStack
is to annotate your body
property as @ViewBuilder
, like this:
@ViewBuilder
var body: some View {
if user.isLoggedIn {
MainView()
} else {
LoginView()
}
}