fs_*_*gre 4 arrays dictionary uipickerview swift
如何将字典中的数据加载到Swift中的PickerView?
我有一个带有String键(状态)和Double值(税)的字典,我想要做的是能够将键设置为titleForRowUIPickerView并key在a中显示所选的值textField.
// Ideal Dictionary
private var states:[String:Double] = ["Alabama":6.000, "Illinois":7.000, "Oregon":8.000, "Wisconsin":9.000]
Run Code Online (Sandbox Code Playgroud)
我能够使用两个数组执行上面描述的操作,一个用于状态,一个用于税收,但我拒绝认为从字典加载是不可能的.
这是我目前的工作,但使用两个数组.
// 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]
}
Run Code Online (Sandbox Code Playgroud)
有什么改进上述代码的建议吗?
vac*_*ama 17
字典是无序的,因此最好使用数组.您可以使用一组命名元组将数据保存在一个数组中:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4170 次 |
| 最近记录: |