如何在SwiftUI中创建单选按钮?

时间:2019-10-27 13:53:12

标签: swiftui

我想对用户的选择做出反应。类似于以下示例:4 Radiobuttons

在第二阶段,我想在每个单选按钮下方显示其他内容,例如相互移动按钮2和3,以提供允许访问的网站列表。

到目前为止,我还没有找到如何在SwiftUI中做到这一点。 提前非常感谢!

4 个答案:

答案 0 :(得分:5)

检查一下...一个易于使用的iOS SwiftUI RadiobuttonGroup

您可以像这样使用它:

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

这是代码:

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()
    }
}

enter image description here

答案 1 :(得分:2)

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

这是2019 swiftUI Essentials主题演讲(SwiftUI Essentials - WWDC 2019中的代码。在视频中大约43分钟,它们显示了此示例。

它看起来像这样:

radio button group

答案 2 :(得分:1)

我使用的是swift4,Catalina OS和Xcode 11.2,并存在无法在iOS上使用RadioGroupPickerStyle的问题,而.radiogroup却无法正常工作(在构建中冻结),所以我制作了自己的可在其他场合使用的软件。 (请注意,它只是一个按钮,因此您必须自己处理逻辑。)希望它会有所帮助!

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()}
        }
    }
}
}

要使用:将其放在任何文件中,就可以像在项目中其他任何地方使用任何其他视图一样使用它。 (我们保留一个包含按钮文件的全局文件夹)

答案 3 :(得分:0)

我刚刚通过添加Binding而不是didTapActivedidTapInactive来编辑@LizJ答案,这样看起来就像其他SwiftUI元素

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}
            }
        }
    }
}