我注意到有時我可以在 SwiftUI 的結果生成器中使用 if-else 陳述句就好了。例如,在體內:
struct MyView: View {
var body: some View {
if foo {
Text("foo")
}
}
}
但是,有時我不能,例如,內部視圖修飾符:
func body(content: Content) -> some View {
content
.toolbar {
if foo { Button("foo") {} }
}
}
}
這上面給了我錯誤說:
Closure containing control flow statement cannot be used with result builder 'ToolbarContentBuilder'
這太令人困惑了。為什么它們不同?我什么時候可以使用 if-else,什么時候應該避免(在那種情況下,為什么它不好?我該怎么辦?)
編輯:
我試圖將按鈕放在Group {}工具列下的 a 下。它也不起作用:
.toolbar {
Group {
if true { // can't put if here
Button("foo")
得到這個錯誤:
Closure containing control flow statement cannot be used with result builder 'CommandsBuilder'
uj5u.com熱心網友回復:
ToolbarContentBuilder 不允許使用 if 陳述句,它旨在使用ToolbarItemGroup,您可以像常規 ViewBuilder 一樣使用 if :
var body: some View {
NavigationView {
Text("Hello, world!")
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if foo { Button("foo") {} }
}
}
}
}
uj5u.com熱心網友回復:
SwiftUI 用于ResultBuilder構建視圖。John Sundell 有一篇很好的深入探討它們的文章。
是否可以使用 anif取決于視圖使用的結果構建器,特別是它是否實作buildIf/buildOptional方法。
支持結果構建器的一個含義if是結果中可以有 0 個視圖。
無論出于何種原因,實作者toolbar已經決定工具列中必須有一些內容,并且他們使用的結果生成器ToolBarContentBuilder沒有實作支持條件陳述句所需的方法。
你是對的,這有點令人困惑。不幸的是,找出在特定背景關系中是否支持條件的唯一方法是嘗試或通讀檔案以找到元素使用的結果構建器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427054.html
