Home > Enterprise >  Swift UITableViewCell not showing Labels
Swift UITableViewCell not showing Labels

Time:09-27

I'm trying to create a custom cell view with some labels, I have created a subclass of UITableViewCell and connected the labels to it. Inside cellForRowAt method I dequeued the cell and cast it as YourCell subclass to access the labels and set text.

Setting class of cell to YourCell

However when running the app, nothing is showing up.

class YourCell: UITableViewCell {
    
    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    
    @IBOutlet weak var label3: UILabel!
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    let array1 = ["Name1", "Name2","Name3","Name3"]
    let array2 = ["1","2","3","4"]
    let array3 = ["18","17","11","9"]
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.delegate = self
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! YourCell
        cell.label1.text = array1[indexPath.row]
        cell.label2.text = array2[indexPath.row]
        cell.label3.text = array3[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array2.count
    }


}

CodePudding user response:

You have conformed the UITableViewDelegate protocol correctly, the only thing you are missing is to set up your datasource by including this line in your viewDidLoad.

tableview.dataSource = self
  • Related