SwiftUI - Сохранение значения выбора кнопок - PullRequest
0 голосов
/ 14 апреля 2020

У меня есть HStack кнопок, которые пользователь может выбрать, которые действуют как переключатели. У меня проблемы с выяснением, как сохранить выбор пользователя. Я перетаскиваю MyRadioButtons() в другое представление и думаю, что моя задача состоит в том, чтобы получить доступ к 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]})

1 Ответ

1 голос
/ 15 апреля 2020

Это должно сделать это:

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!")
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...