根据字符串更改选择UiPickerView文本

问题描述 投票:1回答:1

嗨,我有一个带字符串的UIPickerView,我想要的是选择基于字符串的文本:我尝试用伪语言解释自己,我想得到的是这样的:

if uipicker.gettext ()! = "mystring" {
    uipicker.selectext("mystring)
}

我怎么能迅速得到这个?

swift uipickerview
1个回答
2
投票

你很可能有一个Array的字符串来填充你的选择器,假设你有:

let data = ["string 1", "string 2", "string 3"]

你实现了这样的UIPickerView

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return data.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return data[row]
}

然后,您可以创建一个方法,使给定的String选择选择器中的行

func selectPicker(withText text: String) {
    if let index = data.index(of: text) {
        picker.selectRow(index, inComponent: 0, animated: true)
    } else {
        print("text not found")
    }
}

你完成了:)

© www.soinside.com 2019 - 2024. All rights reserved.