如何在Swift 3中的UIPickerView中获取所选行的String值?

时间:2018-01-11 06:50:07

标签: ios swift uipickerview

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    switch pickerView {
    case sexPicker:
        return sex.count
    case agePicker:
        return age.count
    case proPicker:
        return profession.count
    default:
        return 0
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    switch pickerView {
    case sexPicker:
        return sex[row]
    case agePicker:
        return age[row]
    case proPicker:
        return profession[row]
    default:
        return ""
    }
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    switch pickerView {
    case sexPicker:
        sexText.text = sexPicker.selectedRow(inComponent: 1) *// This gives only the row value but  need string value*
    case agePicker:
        ageText.text = agePicker.selectedRow(inComponent: 1)
    case proPicker:
        professionText.text = pickerView(proPicker, titleForRow: 0, forComponent: 1)    // Cannot call non-function type uipickerview
    default:
        break
    }
}

请帮助我获取特定选择器视图的选定行的字符串值。

2 个答案:

答案 0 :(得分:6)

很简单。请使用数据模型。

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

    switch pickerView {
    case sexPicker:
        sexText.text = sex[row] 
    case agePicker:
        ageText.text = age[row]
    case proPicker:
        professionText.text = profession[row]
    default:
        break
    }

}

答案 1 :(得分:0)

onLiveChange