SwiftUI sheet 闭包捕获列表语法
SwiftUI sheet closure capture list syntax
如何将捕获列表添加到 SwiftUI .sheet(content: ) 闭包?
我在 SwiftUI 和 content: 闭包中有一个 sheet,我检查可选值以确定显示哪个视图。第一次是 运行 即使我事先设置了它,该值也总是 nil 。我提交了一份错误报告,Apple 说如果我在闭包的捕获列表中引用该变量,那么它将按预期工作。我是 SwiftUI 的新手,一直无法弄清楚这样做的正确语法。语法是什么?
struct ContentView: View {
@State var presentButtonTwoDetail: Bool = false
@State var seletedIndex: Int? = nil
var body: some View {
Text("Hello")
.sheet(isPresented: $presentButtonTwoDetail) {
selectedIndex = nil
} content: {
{
[selectedIndex] // This syntax won't compile
() -> View in
if let theIndex = selectedIndex {
DetailView(selectedIndex: theIndex)
} else {
// This gets called on the first run only even when the `selectedIndex` is not nil.
DetailView(selectedIndex: 0)
}
}
}
}
}
编译通过。
struct ContentView: View {
@State var presentButtonTwoDetail: Bool = false
@State var selectedIndex: Int? = nil
var body: some View {
Text("Hello")
.sheet(isPresented: $presentButtonTwoDetail) {
selectedIndex = nil
} content: { [selectedIndex] in
if let theIndex = selectedIndex {
DetailView(selectedIndex: theIndex)
} else {
DetailView(selectedIndex: 0)
}
}
}
}
如何将捕获列表添加到 SwiftUI .sheet(content: ) 闭包?
我在 SwiftUI 和 content: 闭包中有一个 sheet,我检查可选值以确定显示哪个视图。第一次是 运行 即使我事先设置了它,该值也总是 nil 。我提交了一份错误报告,Apple 说如果我在闭包的捕获列表中引用该变量,那么它将按预期工作。我是 SwiftUI 的新手,一直无法弄清楚这样做的正确语法。语法是什么?
struct ContentView: View {
@State var presentButtonTwoDetail: Bool = false
@State var seletedIndex: Int? = nil
var body: some View {
Text("Hello")
.sheet(isPresented: $presentButtonTwoDetail) {
selectedIndex = nil
} content: {
{
[selectedIndex] // This syntax won't compile
() -> View in
if let theIndex = selectedIndex {
DetailView(selectedIndex: theIndex)
} else {
// This gets called on the first run only even when the `selectedIndex` is not nil.
DetailView(selectedIndex: 0)
}
}
}
}
}
编译通过。
struct ContentView: View {
@State var presentButtonTwoDetail: Bool = false
@State var selectedIndex: Int? = nil
var body: some View {
Text("Hello")
.sheet(isPresented: $presentButtonTwoDetail) {
selectedIndex = nil
} content: { [selectedIndex] in
if let theIndex = selectedIndex {
DetailView(selectedIndex: theIndex)
} else {
DetailView(selectedIndex: 0)
}
}
}
}