使用自定义单元格时不会调用Table View委托方法

时间:2019-07-17 09:48:12

标签: ios swift

我正在使用自定义单元格来显示列表。在我的代码中,我发现未调用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
    }
}

3 个答案:

答案 0 :(得分:0)

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

  1. 设置UITableView代表

  2. 在下一行进行更正

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

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

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

答案 1 :(得分:0)

  • 为TableView设置委托和数据源,例如

tblVw.dataSource =自我

tblVw.delegate =自我

或仅使用情节提要进行设置。

  • 也可以在tableView“大小检查器选项卡”中检查单元格的大小

答案 2 :(得分:0)

viewDidLoad 中添加以下两行代码:

medcineCell.delegate = self
medcineCell.dataSource = self

cellForRowAt 中,最好编写如下代码:

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