【问题标题】:How to create a radio button group with custom PickerStyle?如何使用自定义 PickerStyle 创建单选按钮组?
【发布时间】:2020-05-18 12:08:34
【问题描述】:

PickerStyle 提供 WheelPickerStyle、SegmentedPickerStyle 等。我想自定义它创建一个单选按钮,一次只能选择一个。

我是 Android 开发人员,对 swift 非常陌生。我正在使用 SwiftUI 来满足我的 UI 需求。

我查看了文档,发现有一个 PickerStyle 协议,但我无法实现它,也没有找到任何教程。我有以下代码:

struct RadioPickerStyle: PickerStyle {

    static func _makeView<SelectionValue>(value: _GraphValue<_PickerValue<RadioPickerStyle, SelectionValue>>, inputs: _ViewInputs) -> _ViewOutputs where SelectionValue : Hashable {
//        Text("\(value)")
    }

    static func _makeViewList<SelectionValue>(value: _GraphValue<_PickerValue<RadioPickerStyle, SelectionValue>>, inputs: _ViewListInputs) -> _ViewListOutputs where SelectionValue : Hashable {
//        List(inputs) {
//            ForEach
//        }
    }

我想在下面的代码中使用它:

...
    @State var gender: Int = 0
    let genderOptions: [String] = ["Male", "Female", "Other"]
...
                    Picker("Gender", selection: $gender) {
                        ForEach(0 ..< genderOptions.count) { option in
                            Text(self.genderOptions[option])
                                .tag(self.gender)
                        }
                    }
                    .pickerStyle(RadioPickerStyle())
...

谁能告诉我_ViewInputs_ViewOutputs_ViewListInputs_ViewListOutputs是什么?

【问题讨论】:

  • 那些是私有类型...现在不允许自定义PickerStyle
  • 奇怪! o_O 为什么他们允许我在 RadioPickerStyle 结构上实现 PickerStyle
  • 如果你真的实现了,这里就不会有这个问题了。 ;)
  • 我的意思是,我可以写struct RadioPickerStyle: PickerStyle,我在这里没有收到任何错误..
  • 无论如何,我知道下划线类是私有的,我不能让我的 PickerStyle :(

标签: ios swift xcode uikit swiftui


【解决方案1】:

使用此代码,您可以在所选变量中获得标记值。

@State private var selected : Int = 0

Picker("Gender:", selection: $selected){
    Text("Male").tag(0)
    Text("Female").tag(1)
    Text("Male").tag(0)   
}.pickerStyle(RadioPickerStyle())

Text("\(selected)")

【讨论】:

  • RadioPickerStyle 现在似乎在 iOS 中不可用。
猜你喜欢
  • 1970-01-01
  • 2021-12-26
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2015-12-07
  • 1970-01-01
相关资源
最近更新 更多