How do I implement radio buttons in swift

Asked on 07/30/2024

1 search

To implement radio buttons in Swift, you can use the Picker view in SwiftUI, which is designed to allow users to select a single value from a list of options. Here's a basic example of how you can create radio buttons using Picker:

import SwiftUI

struct RadioButtonExample: View {
    @State private var selectedOption = "Option 1"
    let options = ["Option 1", "Option 2", "Option 3"]

    var body: some View {
        VStack {
            Text("Select an option:")
                .font(.headline)
            
            Picker("Options", selection: $selectedOption) {
                ForEach(options, id: \.self) { option in
                    Text(option).tag(option)
                }
            }
            .pickerStyle(RadioGroupPickerStyle()) // Use RadioGroupPickerStyle for radio button appearance
        }
        .padding()
    }
}

struct RadioButtonExample_Previews: PreviewProvider {
    static var previews: some View {
        RadioButtonExample()
    }
}

In this example:

  • @State private var selectedOption is used to keep track of the selected option.
  • Picker is used to create the radio buttons, with each option being represented by a Text view.
  • .pickerStyle(RadioGroupPickerStyle()) is used to style the Picker as a group of radio buttons.

For more detailed information on SwiftUI controls and their customization, you can refer to the session SwiftUI essentials from WWDC 2024. This session covers various built-in capabilities of SwiftUI, including controls like buttons, toggles, and pickers.