未调用TableViewCell内部的UIPickerView委托



我有一个TableViewCell,它包含一个UIPickerView。问题是,UIPickerView的委托没有被调用

extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "testCell") as! TableViewCell

cell.setupCell(indexPath: indexPath.row)

return UITableViewCell()
}
}
class TableViewCell: UITableViewCell {
public var picker = UIPickerView()
private var index = 1

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
print("awakeFromNib")
picker.dataSource = self
picker.delegate = self        
}

public func setupCell(indexPath: Int) {
print("setupcell")
index = indexPath
contentView.addSubview(picker)

picker.translatesAutoresizingMaskIntoConstraints = false
picker.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor).isActive = true
picker.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor).isActive = true
picker.topAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true

}
}
extension TableViewCell: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {        
return 3
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 10
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "abc"
}
}

我尝试使用picker.reloadAllComponents()重新加载picker,但只调用了func numberOfComponents(in pickerView: UIPickerView)。我错过了什么?我的手机肯定有问题。

您需要返回您设置的单元格,而不是新的单元格UITableViewCell()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "testCell") as! TableViewCell

cell.setupCell(indexPath: indexPath.row)

return cell //UITableViewCell()
}

最新更新