修改嵌套对象中的状态



我是Swift的新手,我遇到了这个问题。我想在工具栏中制作一个播放/暂停按钮,并决定将工具栏代码移动到它自己的对象Toolbar。按钮按下时应该会改变其图像,但当我按下它时,状态不会改变。我做错了什么?

struct ContentView: View {
var body: some View {
NavigationView {
List{
Text("asdf")
}
.toolbar {
Toolbar()
}
}
}
}
struct Toolbar: ToolbarContent {
@State var started = false

var body: some ToolbarContent {
ToolbarItem(id:"start-button", placement: .primaryAction) {
Button(action: {
self.started.toggle()
}) {
Image(systemName: self.started == true ? "pause.fill" : "play.fill")
.foregroundColor(.white)
}
}
}
}

使用双向绑定。

struct ContentView: View {
@State private var started = false //<-- Here

var body: some View {
NavigationView {
List{
Text("asdf")
}
.toolbar {
Toolbar(started: $started) //<-- Here
}
}
}
}
struct Toolbar: ToolbarContent {

@Binding var started: Bool //<-- Here

var body: some ToolbarContent {
ToolbarItem(id:"start-button", placement: .primaryAction) {
Button(action: {
self.started.toggle()
}) {
Image(systemName: self.started ? "pause.fill" : "play.fill")
.foregroundColor(.white)
}
}
}
}

@State仅在View内部工作,而ToolbarContent不是View

您应该将@State started保留在ContentView中,并将其包装后的值传递给工具栏。然后,使用闭包对其进行更新。

struct ContentView: View {
@State var started = false

var body: some View {
NavigationView {
List{
Text("asdf")
}
.toolbar {
Toolbar(started: started) {
started.toggle() /// executed when `pressed` is called
}
}
}
}
}
struct Toolbar: ToolbarContent {
var started: Bool
var pressed: (() -> Void) /// closure here!

var body: some ToolbarContent {
ToolbarItem(id:"start-button", placement: .primaryAction) {
Button(action: {
pressed() /// call the closure
}) {
Image(systemName: self.started == true ? "pause.fill" : "play.fill")
.foregroundColor(.white)
}
}
}
}

最新更新