根据字符串更改 select UiPickerView 文本
Change select UiPickerView text based on a string
你好我有一个 UIPickerView
里面有字符串,我想要的是 select 基于字符串的文本:我试着用伪语言来解释自己,我想要什么得到的是这样的:
if uipicker.gettext ()! = "mystring" {
uipicker.selectext("mystring)
}
我怎样才能在 swift 中得到这个?
您很可能有 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")
}
}
大功告成:)
你好我有一个 UIPickerView
里面有字符串,我想要的是 select 基于字符串的文本:我试着用伪语言来解释自己,我想要什么得到的是这样的:
if uipicker.gettext ()! = "mystring" {
uipicker.selectext("mystring)
}
我怎样才能在 swift 中得到这个?
您很可能有 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")
}
}
大功告成:)