How to create Radiobuttons in SwiftUI?

Asked 3 years, 1 month ago

Modified 1 year, 11 months ago

Viewed 23k times

25

I would like to react on a choice of a user. Something similar to this example: 

In a 2nd stage would I like to show additional content below each radiobutton, e.g. moving the buttons 2 and 3 from each other in order to give a list of websites for allowing.

So far I haven't found how to do this in SwiftUI. Many thanks in advance!

Share

Improve this question

Follow

asked Oct 27, 2019 at 13:53

Wizard of Kneup

1,65711 gold badge1515 silver badges3333 bronze badges

  • What have you tried so far? 

    – fulvio

     Oct 28, 2019 at 5:01
  • I am only learning SwiftUI and this is my first need. My first idea was to create it all from Scratch as I cannot find examples. By now I decided to go with Cocoa instead as I cannot wait too long right now. :-( 

    – Wizard of Kneup

     Oct 28, 2019 at 19:39

Add a comment

4 Answers

Sorted by:

                                              Highest score (default)                                                                   Trending (recent votes count more)                                                                   Date modified (newest first)                                                                   Date created (oldest first)                              

43

Picker(selection: $order.avocadoStyle, label: Text("Avocado:")) { 
    Text("Sliced").tag(AvocadoStyle.sliced) 
    Text("Mashed").tag(AvocadoStyle.mashed)
}.pickerStyle(RadioGroupPickerStyle())

This is the code from the 2019 swiftUI essentials keynote (SwiftUI Essentials - WWDC 2019. Around 43 minutes in the video they show this example.

It will look like this:

Share

Improve this answer

Follow

edited Feb 1, 2020 at 7:08

onmyway133

44.1k2626 gold badges253253 silver badges258258 bronze badges

answered Oct 28, 2019 at 21:03

user12132829

  • How to Create .radioGroup? 

    – Achal Gandhi

     Nov 25, 2019 at 12:22
  • It’s a predefined type but it could be renamed to RadioGroupPickerStyle. .pickerStyle(RadioGroupPickerStyle())  

    – user12132829

     Nov 25, 2019 at 23:34 
  • 'RadioGroupPickerStyle' has been explicitly marked unavailable here (SwiftUI.RadioGroupPickerStyle) I am getting above error 

    – Achal Gandhi

     Nov 26, 2019 at 9:27 
  • 3

    I think radio buttons are not natively supported for iOS. 

    – user12132829

     Nov 26, 2019 at 14:23
  • 17

    Please note that RadioGroupPickerStyle is supported on Mac only (so no iOS) 

    – msk

     Apr 5, 2020 at 16:26

Add a comment

33

check this out...an easy to use SwiftUI RadiobuttonGroup for iOS

you can use it like this:

RadioButtonGroup(items: ["Rome", "London", "Paris", "Berlin", "New York"], selectedId: "London") { selected in
                print("Selected is: \(selected)")
            }

and here is the code:

struct ColorInvert: ViewModifier {

    @Environment(\.colorScheme) var colorScheme

    func body(content: Content) -> some View {
        Group {
            if colorScheme == .dark {
                content.colorInvert()
            } else {
                content
            }
        }
    }
}

struct RadioButton: View {

    @Environment(\.colorScheme) var colorScheme

    let id: String
    let callback: (String)->()
    let selectedID : String
    let size: CGFloat
    let color: Color
    let textSize: CGFloat

    init(
        _ id: String,
        callback: @escaping (String)->(),
        selectedID: String,
        size: CGFloat = 20,
        color: Color = Color.primary,
        textSize: CGFloat = 14
        ) {
        self.id = id
        self.size = size
        self.color = color
        self.textSize = textSize
        self.selectedID = selectedID
        self.callback = callback
    }

    var body: some View {
        Button(action:{
            self.callback(self.id)
        }) {
            HStack(alignment: .center, spacing: 10) {
                Image(systemName: self.selectedID == self.id ? "largecircle.fill.circle" : "circle")
                    .renderingMode(.original)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: self.size, height: self.size)
                    .modifier(ColorInvert())
                Text(id)
                    .font(Font.system(size: textSize))
                Spacer()
            }.foregroundColor(self.color)
        }
        .foregroundColor(self.color)
    }
}

struct RadioButtonGroup: View {

    let items : [String]

    @State var selectedId: String = ""

    let callback: (String) -> ()

    var body: some View {
        VStack {
            ForEach(0..<items.count) { index in
                RadioButton(self.items[index], callback: self.radioGroupCallback, selectedID: self.selectedId)
            }
        }
    }

    func radioGroupCallback(id: String) {
        selectedId = id
        callback(id)
    }
}

struct ContentView: View {
    var body: some View {
        HStack {
            Text("Example")
                .font(Font.headline)
                .padding()
            RadioButtonGroup(items: ["Rome", "London", "Paris", "Berlin", "New York"], selectedId: "London") { selected in
                print("Selected is: \(selected)")
            }
        }.padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ContentViewDark_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        .environment(\.colorScheme, .dark)
        .darkModeFix()
    }
}

Share

Improve this answer

Follow

answered May 22, 2020 at 7:31

Chris

6,90533 gold badges1717 silver badges3737 bronze badges

Add a comment

10

I just edited @LizJ answer , by adding Binding instead of didTapActive & didTapInactive , so like that it will looks like other SwiftUI elements

import SwiftUI
struct RadioButton: View {
    @Binding var checked: Bool    //the variable that determines if its checked
    
    var body: some View {
        Group{
            if checked {
                ZStack{
                    Circle()
                        .fill(Color.blue)
                        .frame(width: 20, height: 20)
                    Circle()
                        .fill(Color.white)
                        .frame(width: 8, height: 8)
                }.onTapGesture {self.checked = false}
            } else {
                Circle()
                    .fill(Color.white)
                    .frame(width: 20, height: 20)
                    .overlay(Circle().stroke(Color.gray, lineWidth: 1))
                    .onTapGesture {self.checked = true}
            }
        }
    }
}

Share

Improve this answer

Follow

answered Dec 16, 2020 at 15:45

Ouail Bellal

1,3741212 silver badges2626 bronze badges

Add a comment

7

I'm using swift4, Catalina OS and Xcode 11.2 and was having the issue where RadioGroupPickerStyle was unavailable for iOS and .radiogroup just didn't work (it froze in build) so I made my own that's reusable for other occasions. (notice its only the button so you have to handle the logic yourself.) Hope it helps!

import SwiftUI

struct RadioButton: View {
let ifVariable: Bool    //the variable that determines if its checked
let onTapToActive: ()-> Void//action when taped to activate
let onTapToInactive: ()-> Void //action when taped to inactivate

var body: some View {
    Group{
        if ifVariable {
            ZStack{
                Circle()
                    .fill(Color.blue)
                    .frame(width: 20, height: 20)
                Circle()
                    .fill(Color.white)
                    .frame(width: 8, height: 8)
            }.onTapGesture {self.onTapToInactive()}
        } else {
            Circle()
                .fill(Color.white)
                .frame(width: 20, height: 20)
                .overlay(Circle().stroke(Color.gray, lineWidth: 1))
                .onTapGesture {self.onTapToActive()}
        }
    }
}
}

TO USE: Put this in any file and you can use it as you would any other view anywhere else in the project. (we keep a global folder that has a buttons file in it)

Share

Improve this answer

Follow

answered Dec 5, 2019 at 15:28

LizJ

711

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值