未调用 TableViewCell 内的 UIPickerView 委托

Posted

技术标签:

【中文标题】未调用 TableViewCell 内的 UIPickerView 委托【英文标题】:UIPickerView delegate inside of TableViewCell not called 【发布时间】:2020-08-04 18:05:27 【问题描述】:

我有一个包含 UIPickerView 的 TableViewCell。问题是,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() 重新加载选择器,但只有func numberOfComponents(in pickerView: UIPickerView) 被调用。我错过了什么?问题肯定出在我的手机上。

【问题讨论】:

【参考方案1】:

您需要返回您设置的单元格而不是新单元格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()
    

【讨论】:

以上是关于未调用 TableViewCell 内的 UIPickerView 委托的主要内容,如果未能解决你的问题,请参考以下文章

TableViewCell 内的 CollectionView

更改 TableViewCell 内的 UIPageControl 的 CurrentPage 时出现问题

TableViewCell 内的 UItextField 包含多个部分 - 数据重复

无法单击 iOS 14 中 TableViewCell 内的按钮 [重复]

原型 tableviewcell 内的 UIPickerView 没有选择指示器

tableviewcell 内的 UIButton 触发单元格而不是按钮 [重复]