我实现了一个带有多个组件的选择器视图的演示
当我将值设置为正确的文本时 我想输出是
one 1
但是设置了
one
1
2
two
下面是我的代码:
var pickdata = [ ["one","Two"],
["1","2"]
]
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickdata.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 2
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickdata[component][row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
activeTextfield.text = pickdata[component][row]
print(pickdata[component][row])
}
答案 0 :(得分:0)
您应该将numberOfRowsInComponent
方法更改为return pick date[0].count
,因为您使用的是二维数组,并且希望返回内部数组中的对象数。
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickdata[0].count
}
我还建议您将数据结构更改为Dictionary<String,String>
,对于这个二维数组的问题来说,这似乎已经足够了。
var pickData = ["one":1,"two":2]
答案 1 :(得分:0)
像@david一样提到将数据结构更改为Dictionary将是正确的方法。如果你正在寻找一个简单的黑客,那么这个代码将有所帮助,虽然它不是最好的方法。对于输出“一1”等等这可能是有用的
var pickDataIndices = ["1", "2"]
var pickData = ["one", "Two"]
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickData.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
activeTextfield.text = pickData[row]
print("%@ %@",pickData[row], pickDataIndices[row])
}