我有一个GroupView
接受绑定作为参数,因为我希望GroupView修改枚举中的数据。
可以帮助我实现这一目标吗?
import SwiftUI
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
GroupView(group: /* What do i put here? */) // <----------------
}
}
}
struct GroupView: View {
@Binding var group: Group
var body: some View {
Text("Hello World")
}
}
class ViewModel : ObservableObject {
@Published var instruction: Instruction!
init() {
instruction = .group(Group(groupTitle: "A Group struct"))
}
}
enum Instruction {
case group(Group)
}
struct Group { var groupTitle: String }
答案 0 :(得分:3)
嗯,这当然可以解决...但是可能有更好的方法解决您的问题。但是,没有哪个人比您更有利于确定这一点。因此,我将回答您有关如何传递绑定的问题。
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
GroupView(group: viewModel.groupBinding)
}
}
}
class ViewModel : ObservableObject {
@Published var instruction: Instruction!
init() {
instruction = .group(Group(groupTitle: "A Group struct"))
}
var groupBinding: Binding<Group> {
return Binding<Group>(get: {
if case .group(let g) = self.instruction {
return g
} else {
return Group(groupTitle: "")
}
}, set: {
self.instruction = .group($0)
})
}
}