gpt4 book ai didi

swift - PickerView ViewForRow 无法识别组件

转载 作者:行者123 更新时间:2023-11-28 07:42:40 25 4
gpt4 key购买 nike

我正在使用多个组件来制作计时器。当我将 pickerView 与 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 函数时,我的数据对于第一列和第二列是正确的。但是我丢失了数据旁边的小时和分钟标签。但是添加它会使我的第二列返回与第一列相同的数据。我错过了什么?

最佳答案

这就是您所需要的。您应该只使用其中一个委托(delegate),titleForRowviewForRow 因为它们都做同样的事情,即给行赋予标题。您的问题出在您实际返回数据的 didSelect 委托(delegate)中。

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
}

关于swift - PickerView ViewForRow 无法识别组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51836741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com