我正在使用多个组件来制作计时器。当我将其与ViewForRow合并时,我的pickerView无法识别我的第二个数据源
let hourDataSource = ["0", "1", "2", "3", "4", "5"]
let minDataSource = ["0", "10", "20", "30", "40", "50"]
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = UILabel()
if component == 0 {
label.text = String(row)
label.textAlignment = .center
} else if component == 1 {
label.text = String(row)
label.textAlignment = .center
}
print(component)
return label
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let label = pickerView.view(forRow: row, forComponent: component) as? UILabel {
if component == 0, row > 1 {
label.text = String(row) + " hours"
} else if component == 0 {
label.text = String(row) + " hour"
} else if component == 1 {
label.text = String(row) + " min"
}
}
//print(component)
let hour = dataSource[pickerView.selectedRow(inComponent: 0)]
let min = minDataSource[pickerView.selectedRow(inComponent: 1)]
timerPickerViewLbl.text = "\(hour):\(min) hrs"
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return dataSource[row]
} else {
return minDataSource[row]
}
}
我正在打印组件,所以我知道它会被调用。删除viewForRow函数时,第一列和第二列的数据正确。但是我丢失了数据旁边的小时和分钟标签。但是添加它会使我的第二列返回与我的第一列相同的数据。我想念什么?
答案 0 :(得分:0)
这就是您所需要的。您应该只使用titleForRow
或viewForRow
这些委托之一,因为他们两个都做相同的事情,即为行赋予标题。您的问题出在didSelect
委托中,您实际上是在返回数据。
let hourDataSource = ["0", "1", "2", "3", "4", "5"]
let minDataSource = ["0", "10", "20", "30", "40", "50"]
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let hour = dataSource[pickerView.selectedRow(inComponent: 0)]
let min = minDataSource[pickerView.selectedRow(inComponent: 1)]
timerPickerViewLbl.text = "\(hour):\(min) hrs"
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0, row > 1 {
return "\(hourDataSource[row]) hours"
} else if component == 0 {
return "\(hourDataSource[row]) hour"
} else if component == 1 {
return "\(minDataSource[row]) mins"
}
return nil
}