Skip to content

Instantly share code, notes, and snippets.

@huycozy
Created September 24, 2025 07:25
Show Gist options
  • Select an option

  • Save huycozy/93b12c030651c4fde6fe8fceda1ba1ee to your computer and use it in GitHub Desktop.

Select an option

Save huycozy/93b12c030651c4fde6fe8fceda1ba1ee to your computer and use it in GitHub Desktop.
build radio in swiftui
//
// ContentView.swift
// iosNativeApp-SwiftUI
//
// Created by Huy M4 on 9/23/25.
//
import SwiftUI
struct ContentView: View {
@State private var selectedOption: String? = nil
let options = ["Option 1", "Option 2", "Option 3", "Option 4"]
var body: some View {
VStack(alignment: .leading, spacing: 20) {
Text("Choose an Option")
.font(.title2)
.fontWeight(.semibold)
.padding(.bottom, 10)
ForEach(options, id: \.self) { option in
RadioButton(
title: option,
isSelected: selectedOption == option
) {
selectedOption = option
}
}
Spacer()
// Show selected option
if let selectedOption = selectedOption {
Text("Selected: \(selectedOption)")
.foregroundColor(.blue)
.padding(.top)
}
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
}
struct RadioButton: View {
let title: String
let isSelected: Bool
let action: () -> Void
var body: some View {
Button(action: action) {
HStack {
Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
.foregroundColor(isSelected ? .blue : .gray)
.font(.title2)
Text(title)
.foregroundColor(.primary)
Spacer()
}
.contentShape(Rectangle()) // Makes the entire row tappable
}
.buttonStyle(PlainButtonStyle()) // Removes default button styling
.accessibilityElement(children: .combine)
.accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton)
.accessibilityLabel(title)
.accessibilityValue(isSelected ? "" : "not selected")
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment