如何使用绑定关联 Swift 枚举? [英] How to use Bind an Associative Swift enum?
本文介绍了如何使用绑定关联 Swift 枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 GroupView
接受绑定作为参数,因为我希望 GroupView 修改枚举中的数据.
I have a GroupView
that accepts a binding as a parameter because I want the GroupView to modify the data in the enum.
有人可以帮助我如何做到这一点吗?
Can some help me on how to accomplish this?
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 }
推荐答案
好吧,这肯定会奏效……但可能有更好的方法来解决您的问题.但没有人比你更能确定这一点.所以我只回答你关于如何传递绑定的问题.
Well, this certainly will work... but probably there's a better approach to your problem. But no one is in a better position than you, to determine that. So I'll just answer your question about how to pass a binding.
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)
})
}
}
这篇关于如何使用绑定关联 Swift 枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文