【问题标题】:UIPickerView select row where title == String in SwiftUIPickerView 在 Swift 中选择 title == String 的行
【发布时间】:2016-09-18 07:52:57
【问题描述】:

我有一个 UIPickerView,我想选择一个 title 等于 String 的行,我从我的 php/mysql 脚本中收到。

假设这是我的数组:

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

这就是我从我的 php 脚本中得到的(这就是我希望我的 UIPickerView 选择的内容。):

let myString = "Second"

所以我的问题是:

我该如何做这样的事情:self.myPicker.selectRow(1, inComponent: 0, animated: true) 但我希望 myPicker 选择标题为“第二”的行。

我发现了这个问题,但它在 Objective-c 中:UIPickerView Set Selected Row by Title

非常感谢!

【问题讨论】:

  • 为什么是-1 ?? :D 怎么了。

标签: arrays swift uipickerview


【解决方案1】:

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

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)
}

【讨论】:

  • 谢谢你,这正是我一直在寻找的 :)
  • 欢迎朋友 :) 编码愉快 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多