Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView and custom UITableViewCell using .xib

In my app I am using a custom tableViewCell using a xib file. I create the .xib file outlet the labels etc to my TableViewCell class

In my ViewController the code I used to populate and show the cell on the table view is as follows:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let transaction = statementArray[indexPath.row]
    let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell
    
    
    
    cell.transAmount.text = String(transaction.transAmount)
    cell.transDesc.text = transaction.transDesc
    cell.transFees.text = String(transaction.transFees)
    
    return cell
}

I am aware that the way tableViews work is that they reuse the cell that goes off the screen. Is the way i am loading the .xib and populating the cell correct? Or do I have to add something to my code?

like image 916
pavlos Avatar asked Sep 13 '25 03:09

pavlos


1 Answers

First you need to register your custom cell with UITableView

yourTableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")

then in UITableView Delegate method cellForRowAt you need to write

let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! StatementCell
cell.textLabel?.text = "Sample Project"
return cell

now you can access your UITableViewCell properties with cell.propertyName

and you must take care that "cellIdentifier" and "forCellReuseIdentifier" both value must be same.

like image 133
devang bhatt Avatar answered Sep 14 '25 16:09

devang bhatt