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

Wiz*_*eup 13 swiftui

我想对用户的选择做出反应。类似于这个例子的东西:4 单选按钮

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

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

Lil*_*aen 27

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

这是 2019 年 swiftUI Essentials主题演讲中的代码(SwiftUI Essentials - WWDC 2019。视频中大约 43 分钟他们展示了这个例子。

它看起来像这样:

单选按钮组

  • 请注意,RadioGroupPickerStyle 仅在 Mac 上受支持(因此 iOS 上不支持) (3认同)
  • 我认为 iOS 本身不支持单选按钮。 (2认同)

Chr*_*ris 18

看看这个......一个易于使用的 SwiftUI RadiobuttonGroup for iOS

你可以这样使用它:

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

这是代码:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Oua*_*lal 12

我刚刚编辑了 @LizJ 答案,添加Binding而不是didTapActive& didTapInactive,这样它看起来就像其他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}
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 9

我正在使用 swift4、Catalina OS 和 Xcode 11.2,并且遇到了 RadioGroupPickerStyle 对于 iOS 不可用并且 .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()}
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

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