【问题标题】:Table View delegate methods are not getting called when using custom cell使用自定义单元格时未调用表视图委托方法
【发布时间】:2019-11-26 02:56:13
【问题描述】:

我正在使用自定义单元格来显示列表。在我的代码中,我发现 tableview 委托没有被调用。

import UIKit

class MedicineViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var medcineCell: UITableView!
    @IBOutlet weak var medInput: UITextField!

    var medicine:[String] = ["Medicine"]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func medInsert(_ sender: UIButton) {

        insertMed()
    }

    func insertMed(){
        medicine.append(medInput.text!)
        let indexPath = IndexPath(row: medicine.count - 1, section: 0)
        medcineCell.beginUpdates()
        medcineCell.insertRows(at: [indexPath], with: .automatic)
        medcineCell.endUpdates()

        medInput.text = ""
        view.endEditing(true)
    }

    @IBAction func savePresc(_ sender: UIButton) {

        dismiss(animated: true, completion: nil)
    }


    }

    extension MedicineViewController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return medicine.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let med = medicine[indexPath.row]

        let cell = medcineCell.dequeueReusableCell(withIdentifier: "MedicineCell")as! MedicineCell
        cell.medTitle.text = med

        return cell
    }
}

【问题讨论】:

  • 首先你没有调用delegate,你甚至没有调用tableviewDataSource的协议来用数据填充tableview
  • 你设置了 medcineCell.delegate = self 和 medcineCell.dataSource 吗?

标签: ios swift


【解决方案1】:

检查以下几点配置是否正确

  1. 设置UITableView委托

  2. 在以下行中进行更正

    let cell = **tableView**.dequeueReusableCell(withIdentifier: "MedicineCell")as! MedicineCell
    
  3. 添加以下功能

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    

希望对您有所帮助!祝你好运

【讨论】:

    【解决方案2】:
    • 为 TableView 设置委托和数据源,如

    tblVw.dataSource = 自我

    tblVw.delegate = 自我

    或者只是使用情节提要设置它。

    • 曾经在tableView“Size Inspector Tab”中检查单元格的大小

    【讨论】:

      【解决方案3】:

      viewDidLoad中添加这两行代码:

      medcineCell.delegate = self
      medcineCell.dataSource = self
      

      cellForRowAt 中最好这样编写代码:

      let cell = medcineCell.dequeueReusableCell(withIdentifier: "MedicineCell", for: indexPath) as! MedicineCell
      

      【讨论】:

        猜你喜欢
        • 2017-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多