Neo Teo Neo Teo - 16 days ago 5
Swift Question

How to display each elements of loop to table row?

how to return each element of loop. I mean i want display each name of this loop to row text. It is only return last element. How can i return all of this?


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)

for last in lastnames {
cellFullname.textLabel?.text = "\(last)"
}
return cellFullname
}

Answer

You don't need a loop for displaying the elements in UITableView

Say you have an array of last names:

var lastnames = ["....

And you want to put each element in a UITableViewCell. Two steps:

  1. Define the amount of cells you need:

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
        return lastnames.count 
    }
    
  2. Update the UITableView with the names:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
    
    
        cellFullname.textLabel?.text = lastnames[indexPath.row]
    
        return cellFullname
    }