我有 2 个 UIPickerView,一个叫 dayPicker,你可以在 1-12 之间选择,而 durationPicker 可以选择天、周、月和年。
代码如下:
class AddNewViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
@IBOutlet weak var dayPicker: UIPickerView!
@IBOutlet weak var durationPicker: UIPickerView!
var durationDay: Double?
var durationType: String?
var durationPickerDataSource = ["Day(s)","Week(s)","Month(s)","Year(s)"];
var dayPickerDataSource = ["1","2","3","4","5","6","7","8","9","10","11","12"];
func numberOfComponentsInPickerView(dayPickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == durationPicker {
return durationPickerDataSource.count;
}
else {
return dayPickerDataSource.count;
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == durationPicker{
durationType = durationPickerDataSource[row]
print("")
print("")
print("\(row): type == \(durationType)")
print("\(row)")
print("")
print("")
return durationType
}
else {
durationDay = Double(dayPickerDataSource[row])
return dayPickerDataSource[row]
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.durationPicker.dataSource = self;
self.durationPicker.delegate = self;
self.dayPicker.dataSource = self;
self.dayPicker.delegate = self;
}
}
当我在模拟器中选择行时,它会正确打印除最后一行打印“Week(s)”之外的所有行。
我对选择器有以下限制:
日期选择器:
持续时间选择器:
最佳答案
复制了你的代码,一切正常。我唯一的猜测是您正在修改数据源,因此选择器委托(delegate)返回了错误的信息。
我测试了你的代码(没有修改),选择器显示正确的值...
编辑:
从评论部分看来,问题在于没有指定 UIPickerView
的 didSelectRow
方法,添加它似乎解决了 OP 的问题(无法详细说明“为什么”虽然......):
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == self.dayPicker{
print("picked \(dayPickerDataSource[row])")
}else {
print("picked \(durationPickerDataSource[row])")
}
}
关于ios - UIPickerView 没有注册正确的最后一行。 swift 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35870910/