Radio Buttons group in SwiftUI

Radio Buttons group in SwiftUI, is not hard to implement classic radio button group in your SwiftUI. Though this project is in very early stage, I will work on this in coming days to enhance its features.

Installation: Add RadioButtonGroup.swift in your SwiftUI project.

Usages: Create model class, must conform to RadioModelable protocol

 class RadioModel: RadioModelable {
    var id: Int
    var isChecked: Bool
    var label: String
    
    required init(id: Int, isChecked: Bool, label: String) {
        self.id = id
        self.isChecked = isChecked
        self.label = label
    }
}

Create data provider class, must conform to RadioDataProviding protocol

class DataProvider<T>: RadioDataProviding where T: RadioModelable {
    @Published var items: [RItem] = []
    
    init() {
        
        self.items = getItems()
    }
    
    func getItems() -> [T] {
        return [T(id: 1, isChecked: true, label: "Radio 1"),
                T(id: 2, isChecked: false, label: "Radio 2"),
                T(id: 3, isChecked: false, label: "Radio 3")]
    }
    
    func toggle(id: Int) {
        for var item in self.items {
            if item.id == id {
                item.isChecked = true
            } else {
                item.isChecked = false
            }
        }
        
        self.objectWillChange.send()
    }
}

Finally add in your view

struct ContentView: View {
    var body: some View {
        SRadioButtonViewGroup(dataProvider: DataProvider<RadioModel>(), selectedItem: getSelectedItemLabel)
    }
    
    func getSelectedItemLabel<T>(item: T) {
        print("selected item : \((item as! RadioModel).label)")
    }
}

Preview

Download source code

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a comment