简体   繁体   English

SwiftUI - 存储按钮选择的值

[英]SwiftUI - Storing Value of Button Selection

I have an HStack of buttons which a user can select that act like radio buttons.我有一个HStack按钮,用户可以使用 select,其作用类似于单选按钮。 I'm having trouble figuring out how to store the user's selection.我无法弄清楚如何存储用户的选择。 I pull MyRadioButtons() into another view, and I think my challenge is how to access the id associated with each button so that I can then store the ID.我将MyRadioButtons()拉到另一个视图中,我认为我的挑战是如何访问与每个按钮关联的id ,以便我可以存储 ID。

I used this answer as a reference and have modified slightly to fit my needs, but this is more or less my code将此答案用作参考并稍作修改以满足我的需要,但这或多或少是我的代码

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

Then in the view the user is interacting with, I have this in a VStack along with some other fields...然后在用户正在与之交互的视图中,我将它与其他一些字段一起放在VStack中......

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

This should do it:这应该这样做:

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

Then you can use it like this:然后你可以像这样使用它:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM