我正在使用Swift编写iPhone应用程序,我对UIPickerview有疑问。
class LanguageChangeViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var changeLanguagePicker: UIPickerView!
var pickerData = ["a", "b", "c", "d", "e", "f", "g", "h"]
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
NSUserDefaults.standardUserDefaults().setInteger(row, forKey: "which")
return pickerData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
whichLanguageChosen = row
println(whichLanguageChosen)
}
override func viewDidLoad() { super.viewDidLoad()
changeLanguagePicker.dataSource = self
changeLanguagePicker.delegate = self
}
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }
}
问题在于语言选择,这个println给出正确的值,但是当我在该行中定位后按“返回”时,它返回奇怪的值:0 - 0,1 - > 5,2-6,... 6-2,7-7 ..此外,当我第一次选择一条线后没有点击“返回”时,即当我在选择器中滚动两次时,它返回正确的价值。那可能是什么?
编辑: 这可能会有所帮助:
在我的firstViewController(后面发送的那个)中,我有
if (NSUserDefaults.standardUserDefaults().objectForKey("which") != nil) {
whichLanguageChosen = NSUserDefaults.standardUserDefaults().objectForKey("which") as Int
}
我把它放在里面,以便他记得当我重新启动应用程序时使用的语言。当我评论这一行时,我得到的值是正确的,显然我不明白NSUserDefaults足以看出为什么这是错误的行,而且,奇怪的模式来自哪里(+ - 4)?
另外,还有另一种方法可以指示我的代码保存whichLanguageChosen的值吗?