UIPickerView select 行,其中标题 == Swift 中的字符串

UIPickerView select row where title == String in Swift

我有一个 UIPickerView 并且我想要 select 标题等于 String 的行,我从我的 php/mysql 脚本中收到它。

假设这是我的数组:

var myArray = ["First","Second","Third","Fourth","Sixth","Seventh"]

这就是我从 php 脚本中得到的(这就是我希望我的 UIPickerView 到 select。):

let myString = "Second"

所以我的问题是:

我如何做这样的事情:self.myPicker.selectRow(1, inComponent: 0, animated: true) 但我希望 myPicker 到 select 行,标题为:"Second".

我找到了这个问题,但它在 objective-c 中:UIPickerView Set Selected Row by Title

非常感谢!

如果您不知道对象在数组中的索引,请尝试这样。

let index = myArray.indexOf(myString)
self.myPicker.selectRow(index, inComponent: 0, animated: true)

如果您正在使用 swift 3,那么找到这样的索引。

let index = myArray.index(of: myString)

编辑: 如果你不确定你的数组是否包含你的字符串,你也可以检查 nil。

if let index = myArray.indexOf(myString) {
    self.myPicker.selectRow(index, inComponent: 0, animated: true)
}