I have a TableViewCell that contains a UIPickerView. The problem is, that the delegate of UIPickerView is not getting called
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"
}
}
I tried to reload picker using picker.reloadAllComponents()
, but then only func numberOfComponents(in pickerView: UIPickerView)
is getting called. What am i missing? The problem is for sure with my cell.
You need to return cell that you setup instead of new cell 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()
}