gpt4 book ai didi

arrays - 如何将字典加载到 UIPickerView

转载 作者:搜寻专家 更新时间:2023-10-31 08:10:18 25 4
gpt4 key购买 nike

如何在 Swift 中将字典中的数据加载到 PickerView 中?

我有一个字典 String键(状态)和 Double值(税)和我想要做的是能够将键设置为 titleForRow的 UIPickerView 并显示所选 key 的值在textField .

// Ideal Dictionary
private var states:[String:Double] = ["Alabama":6.000, "Illinois":7.000, "Oregon":8.000, "Wisconsin":9.000]

我能够使用两个数组来执行上述操作,一个用于州,一个用于税收,但我拒绝认为从字典加载是不可能的。

这是我目前可以使用的,但使用了两个数组。

// Arrays
private var stateName = ["Alabama", "Illinois", "Oregon", "Wisconsin"]
private var stateTax = ["6.000", "7.000", "8.000", "9.000"]

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return stateName.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
inputTaxRate.text = stateTax[row]
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return stateName[row]
}

有什么改进上面代码的建议吗?

最佳答案

字典是无序的,所以最好使用数组。您可以使用一组命名元组将您的数据保存在一个数组中:

let stateInfo:[(name: String, tax: Double)] = [("Alabama", 6.000), ("Illinois", 7.000), ("Oregon", 8.000), ("Wisconsin", 9.000)]

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

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
inputTaxRate.text = stateInfo[row].tax
}

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

关于arrays - 如何将字典加载到 UIPickerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35670825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com