[英]SwiftUI binding boolean if statement (Cannot convert value of type 'Binding<Bool>' to expected condition type 'Bool')
I'm trying to conditionally show a View (not using.sheet) and using a binding boolean returns the error above in the title.我试图有条件地显示一个视图(不使用.sheet)并使用绑定 boolean 在标题中返回上述错误。 If I use self.menuactivated
, no view will be presented upon the @State variable toggle.如果我使用self.menuactivated
,@State 变量切换时不会显示任何视图。 Is there a way around this?有没有解决的办法?
struct ContentView: View {
@State private var menuActivated = false
var body: some View {
NavigationView {
... // code
}
if $menuActivated {
menuView()
}
}
}
I assume this was the intention (menu will be shown over NavigationView on toggle)我认为这是意图(菜单将在切换时显示在 NavigationView 上)
struct ContentView: View {
@State private var menuActivated = false
var body: some View {
ZStack {
NavigationView {
... // code
}
if menuActivated {
menuView()
}
}
}
}
Found a way around it.找到了解决方法。 Embedded the NavigationView
in a VStack
and added the menuView
to the end of it.将NavigationView
嵌入到VStack
中,并将menuView
添加到它的末尾。
struct ContentView: View {
@State private var menuActivated = false
var body: some View {
ZStack {
NavigationView {
... // view code
}
if menuActivated {
menuView()
}
}
}
}
in case if you are looking for condition based view如果您正在寻找基于条件的视图
func getView() -> AnyView {
return AnyView(
//any business logic and view
)
}
and use it like并像使用它一样
self.getView()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.