如何使用绑定Swift Swift枚举?

时间:2019-08-19 18:48:38

标签: swift swiftui

我有一个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 }

1 个答案:

答案 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)
        })
    }
}