SwiftUI-存储按钮选择的价值

时间:2020-04-14 20:38:21

标签: ios swiftui

我有一个HStack按钮,用户可以选择这些按钮,它们的作用类似于单选按钮。我在弄清楚如何存储用户选择时遇到麻烦。我将MyRadioButtons()拉到另一个视图中,我想面临的挑战是如何访问与每个按钮关联的id,以便随后存储ID。

我使用this answer作为参考,并做了一些修改以满足我的需求,但这或多或少是我的代码

struct MyRadioButton: View {
    let id: Int
    @Binding var currentlySelectedId: Int
    var body: some View {
        Button(action: { self.currentlySelectedId = self.id }, label: { Text("Tap Me!") })
            .foregroundColor(id == currentlySelectedId ? .green : .red)
    }
}


struct MyRadioButtons: View {
    @State var currentlySelectedId: Int = 0
    var body: some View {
        VStack {
            MyRadioButton(id: 1, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 2, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 3, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 4, currentlySelectedId: $currentlySelectedId)
        }
    }
}

然后在用户正在与之交互的视图中,我将其与其他字段一起放在VStack中...

     MyRadioButtons()
     Button(action: {
     item.selection = [RadioButton ID Here]})

1 个答案:

答案 0 :(得分:1)

这应该做到:

struct MyRadioButton: View {
    let id: Int
    @Binding var currentlySelectedId: Int
    var body: some View {
        Button(action: { self.currentlySelectedId = self.id }, label: { Text("Tap Me!") })
            .foregroundColor(id == currentlySelectedId ? .green : .red)
    }
}


struct MyRadioButtons: View {
    init(selection: Binding<Int>) {
        self._currentlySelectedId = selection
    }
    @Binding var currentlySelectedId: Int
    var body: some View {
        VStack {
            MyRadioButton(id: 1, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 2, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 3, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 4, currentlySelectedId: $currentlySelectedId)
        }
    }
}

然后您可以像这样使用它:

struct ContentView: View {
    @State var selection: Int = 0

    var body: some View {
        VStack {
            MyRadioButtons(selection: $selection)
            Button(action: {
                //whatever
            }) {
                Text("Click me!")
            }
        }
    }
}