[英]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.