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 aText
view..pickerStyle(RadioGroupPickerStyle())
is used to style thePicker
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.

SwiftUI essentials
Join us on a tour of SwiftUI, Apple’s declarative user interface framework. Learn essential concepts for building apps in SwiftUI, like views, state variables, and layout. Discover the breadth of APIs for building fully featured experiences and crafting unique custom components. Whether you’re brand new to SwiftUI or an experienced developer, you’ll learn how to take advantage of what SwiftUI has to offer when building great apps.

Catch up on accessibility in SwiftUI
SwiftUI makes it easy to build amazing experiences that are accessible to everyone. We’ll discover how assistive technologies understand and navigate your app through the rich accessibility elements provided by SwiftUI. We’ll also discuss how you can further customize these experiences by providing more information about your app’s content and interactions by using accessibility modifiers.

Migrate your TVML app to SwiftUI
SwiftUI helps you build great apps on all Apple platforms and is the preferred toolkit for bringing your content into the living room with tvOS 18. Learn how to use SwiftUI to create familiar layouts and controls from TVMLKit, and get tips and best practices.