How to create Radiobuttons in SwiftUI?

痴心易碎 提交于 2019-12-11 14:14:17

问题


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!


回答1:


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

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:




回答2:


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)



来源:https://stackoverflow.com/questions/58580027/how-to-create-radiobuttons-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!