我发现了这个问题-What is the best way to switch views in SwiftUI?-但我无法获得为我工作的答案。
struct view4x: View {
@State var goView: Bool = false
var body: some View {
if goView {
view5x(goView1: self.$goView)
} else {
Form {
/* ... */
}
}
}
}
按钮位于表单内部:
Button(action: {
self.goView.toggle()
}) {
Text("Catalog")
}
对于其他观点,我有:
struct view5x: View {
@Binding var goView1: Bool
var body: some View {
Text("TEST")
Button(action: {
self.goView1.toggle()
}) {
Text("Return")
}
}
}
我只是得到两个主体都声明不透明返回类型的错误。它不会预览。
答案 0 :(得分:1)
好的,这是您观点中的类似错误。为了更好地了解它们,请查看View
协议:
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required `body` property.
associatedtype Body : View
/// Declares the content and behavior of this view.
var body: Self.Body { get }
}
因此,body
只是一个计算变量,它应该返回some View
。您在view5x
中的错误是,您将2个不同的视图改为1个。这里的解决方案是将它们嵌入VStack
中,例如:
struct view5x: View{
@Binding var goView1: Bool
var body: some View{
VStack {
Text("TEST")
Button(action: {
self.goView1.toggle()
}) {
Text("Return")
}
}
}
}
与view4x
类似的问题-我认为由于if...else
语句,不清楚哪个视图返回主体。您可以用相同的方式修复它:
struct view4x: View {
@State var goView: Bool = false
var body: some View {
VStack {
if goView {
view5x(goView1: $goView)
} else {
Button(action: {
self.goView.toggle()
}) {
Text("Catalog")
}
}
}
}
}
另一种方法是说如果将每个正文都包装到AnyView
中并在前面键入return
,正文应该返回哪个视图。在此示例中,goView
的更改不会切换视图,但是您可以看到其他语法:
struct view4x: View {
@State var goView: Bool = false
var body: some View {
if goView {
return AnyView(view5x(goView1: $goView))
} else {
return AnyView(Button(action: {
self.goView.toggle()
}) {
Text("Catalog")
})
}
}
}