[英]SwiftUI - Storing Value of Button Selection
我有一个HStack
按钮,用户可以使用 select,其作用类似于单选按钮。 我无法弄清楚如何存储用户的选择。 我将MyRadioButtons()
拉到另一个视图中,我认为我的挑战是如何访问与每个按钮关联的id
,以便我可以存储 ID。
我将此答案用作参考并稍作修改以满足我的需要,但这或多或少是我的代码
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]})
这应该这样做:
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!")
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.