SwiftUI 中的 EmptyView 是一个只有空内容的视图,用于在需要返回一个视图但不需要任何实际内容时使用。以下是一个使用 EmptyView 的示例代码:
struct ContentView: View {
var body: some View {
VStack {
Text("Some content here.")
if shouldShowEmptyView() {
EmptyView()
} else {
Text("Some more content here.")
}
}
}
func shouldShowEmptyView() -> Bool {
// logic to determine whether to show the empty view or not
return true
}
}
在上面的示例代码中,如果 shouldShowEmptyView() 方法返回 true,则会显示 EmptyView。否则,将显示 “Some more content here.” 的文本视图。
EmptyView 可以作为占位符使用,以确保在某些条件下保持布局的稳定性,例如:
struct ContentView: View {
var body: some View {
VStack {
Text("Some content here.")
if shouldShowEmptyView() {
EmptyView()
}
}
}
func shouldShowEmptyView() -> Bool {
// logic to determine whether to show the empty view or not
return true
}
}
在上面的示例代码中,如果 shouldShowEmptyView() 方法返回 true,则 EmptyView 是唯一的子视图。但是,它的存在可以确保在条件变为真时,该布局保持稳定。