在SwiftUI中显示一个空视图 [英] Displaying an empty view in SwiftUI
问题描述
在SwiftUI中,经常需要根据某些条件显示空"视图,例如:
In SwiftUI there's frequently a need to display an "empty" view based on some condition, e.g.:
struct OptionalText: View {
let text: String?
var body: some View {
guard let text = text else { return }
return Text(text)
}
}
不幸的是,由于 guard
的正文必须返回某些视图,因此该代码无法编译,当 text
为 nil <时,该视图为空"视图/code>.当
text
为 nil
时,应如何重写此示例,以便编译并呈现空"视图?
Unfortunately, this doesn't compile since the body of guard
has to return some view, that is an "empty" view when text
is nil
. How should this example be rewritten so that it compiles and renders an "empty" view when text
is nil
?
推荐答案
您必须返回一些内容.如果在某些情况下您不希望显示任何内容,请显示"一个... EmptyView
;)
You have to return something. If there is some condition where you want to display nothing, "display" an...EmptyView
;)
var body: some View {
Group {
if text != nil {
Text(text!)
} else {
EmptyView()
}
}
}
SwiftUI DSL将要求您将if/else包装在 Group
中,并且DSL没有保护/如果让其命名.
The SwiftUI DSL will require you to wrap the if/else in a Group
and the DSL has no guard/if let nomenclature.
这篇关于在SwiftUI中显示一个空视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!