How to Create Radio Button in SwiftUI

Learn how to create Radio button in SwiftUI Based project

how-to-create-radio-button-in-swiftUI-ios14

  1. Create Swift file RadioButtonField.swift
import SwiftUI

//MARK:- Radio Button Field
struct RadioButtonField: View {
    let id: String
    let label: String
    let size: CGFloat
    let color: Color
    let bgColor: Color
    let textSize: CGFloat
    let isMarked:Bool
    let callback: (String)->()
    
    init(
        id: String,
        label:String,
        size: CGFloat = 20,
        color: Color = Color.black,
        bgColor: Color = Color.black,
        textSize: CGFloat = 14,
        isMarked: Bool = false,
        callback: @escaping (String)->()
        ) {
        self.id = id
        self.label = label
        self.size = size
        self.color = color
        self.bgColor = bgColor
        self.textSize = textSize
        self.isMarked = isMarked
        self.callback = callback
    }
    
    var body: some View {
        Button(action:{
            self.callback(self.id)
        }) {
            HStack(alignment: .center) {
                Image(systemName: self.isMarked ? "largecircle.fill.circle" : "circle")
                    .clipShape(Circle())
                    .foregroundColor(self.bgColor)
                Text(label)
                    .font(Font.system(size: textSize))
                Spacer()
            }.foregroundColor(self.color)
        }
        .foregroundColor(Color.white)
    }
}

2. Main View

import SwiftUI

struct ContentView: View {
@State var gender = ""
    var body: some View {
        HStack {
            Text("Gender").font(.headline)
            HStack{
                RadioButtonField(
                    id: "Male",
                    label: "Male",
                    color:.red,
                    bgColor: .blue,
                    isMarked: $gender.wrappedValue == "Male" ? true : false,
                    callback: { selected in
                        self.gender = selected
                        print("Selected Gender is: \(selected)")
                    }
                )
                RadioButtonField(
                    id: "Female",
                    label: "Female",
                    color:.red,
                    bgColor: .blue,
                    isMarked: $gender.wrappedValue == "Female" ? true : false,
                    callback: { selected in
                        self.gender = selected
                        print("Selected Gender is: \(selected)")
                    }
                )
            }
        }
    }


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
       ContentView()
    }
}
how-to-create-radio-button-in-swiftUI-ios14

Leave a Reply

%d bloggers like this: