Skip to main content
 首页 » 数据库

swift之如何使用字典来填充选择器 View (swift)

2024年01月01日64虾米哥

在 Swift 中使用字典填充 UIPickerView 时,如何指定键用作行的标题,而值用于执行计算,例如设置 selectedPower 的值,如下所示?

如果我使用 float 数组,我会按如下方式设置它,但我如何使用字典来实现呢?

class DiagnosticORViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { 
 
var selectedPower : Float! 
 
let FitAssessment : [String : Float] = ["0.50 flat" : -0.50, "0.25 flat" : -0.25, "aligned" : 0, "0.25 steep" : 0.25, "0.50 steep" : 0.50] 
 
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { 
 
    return 1     
} 
 
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { 
 
    return FitAssessment.count    
} 
 
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { 
 
    return "\(FitAssessment[row])" 
} 
 
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { 
 
    selectedPower = FitAssessment[row]    
} 

请您参考如下方法:

两个独立的数组解决了这个问题。

class DiagnosticORViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { 
 
var selectedPower : Float! 
 
let FitDescription : [String] = ["0.50 flat", "0.25 flat", "aligned", "0.25 steep", "0.50 steep"] 
 
let FitValue : [Float] = [ -0.50, -0.25, 0,  0.25, 0.50] 
 
 
@IBOutlet weak var fitAssessmentPicker: UIPickerView! 
 
 
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { 
 
    return 1 
 
} 
 
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { 
 
    return FitDescription.count 
 
} 
 
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { 
 
    return FitDescription[row] 
 
} 
 
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { 
 
    selectedPower = FitValue[row] 
}