【问题标题】:Getting selected value of a UIPickerViewControl in Swift在 Swift 中获取 UIPickerViewControl 的选定值
【发布时间】:2014-10-31 12:09:50
【问题描述】:

如何在 Swift 中获取 UIPickerViewControl 的选定值?

我尝试过这样的事情:

labelTest.text = Spinner1.selectedRowInComponent(0).description

但这只会返回选定的索引。我需要价值。

谁知道怎么做?

【问题讨论】:

  • 让 selectedValue = rolePicker.selectedRowInComponent(0) 给我一个值。另外, let selectedValue = rolePicker.selectedRowInComponent(0).hashValue 也可能给你一些用处。

标签: xcode swift ios8


【解决方案1】:

您必须将选择器视图委托设置为 self 并覆盖此函数

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
   {
        // use the row to get the selected row from the picker view
        // using the row extract the value from your datasource (array[row])
    }

您可以根据自己的使用情况使用它来提取

var selectedValue = pickerViewContent[pickerView.selectedRowInComponent(0)]

pickerViewContent 是你的数据源数组

【讨论】:

  • 我了解最后一种方法,但是如何检索我的数据源数组?
  • 你在哪里为选择器视图设置了数据源,你必须在同一个类中设置它。
  • 我喜欢第一个选项的高级概念。 :)
【解决方案2】:

Swift 3:假设您希望选择每一行的字符串值

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        let valueSelected = yourDataSourceArray[row] as String
 }

【讨论】:

    【解决方案3】:

    斯威夫特 4

    let selectedYearPicker = pickerData[yearPicker.selectedRow(inComponent: 
    print(selectedYearPicker)
    

    或者

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent  component: Int) {
        let yearValueSelected = pickerData[row] as String
        print(yearValueSelected)
    }
    

    【讨论】:

      【解决方案4】:

      到目前为止,所有答案都假定您可以轻松地将所选行连接回原始数据数组。如果你能做到这一点,解决方案相当简单,但这个问题专门解决了原始数组不容易获得的情况。例如,我在表格单元格中有 3 个选择器,当点击一行时它们会展开,它们显示 3 个不同的数组。

      如果我可以简单地从选择器本身检索选定的文本,也许在我的自定义单元格的代码中,而不是必须弄清楚哪个选择器、哪个数据数组、哪一行等等,这会为我省去很多麻烦开。

      如果答案是你不能,那没关系,我会全部解决的。但问题是是否有捷径。

      【讨论】:

      • 没关系。回到选择器输入数据数组的选定行比我想象的要容易。不需要捷径,即使有捷径。
      【解决方案5】:

      接受的答案是正确的,只是它应该包含从 String 到 Int 的类型转换:

      var selectedValue = pickerViewContent[Int(pickerView.selectedRowInComponent(0))!]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-13
        • 2022-11-12
        • 2021-11-24
        • 2014-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多