Alison
Alison

Reputation: 41

how to add list items in table view in swift 5

I am trying to add items to a table view. I can see that everytime I click on the button a new row inserts into the table, but the cell is empty. When I debug the code I can see all the items in the list but I cannot see them displayed on the app itself. The items "1", "2" and "3" are not displayed as well

@IBOutlet weak var itemLbl: UITextField!
    var items: [String] = ["1", "2", "3"]

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: CGRect.zero)


    }

func insertItem(){
    items.append(itemLbl.text!)

    let indexPath = IndexPath(row: items.count - 1,section: 0 )
    tableView.beginUpdates()
    tableView.insertRows(at: [indexPath], with: .automatic)
    tableView.endUpdates()
    itemLbl.text = ""
    view.endEditing(true)
}

So the insert does work, but I just cannot display the text in the table. I do get a new cell for every item that I add, but its just white empty space, instead of the value that I just added

EDIT:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let itemLbl  =  items[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell") as! ItemCell

        cell.itemLbl.text = itemLbl
        return cell
    }

Upvotes: 3

Views: 3669

Answers (3)

surfmaster96
surfmaster96

Reputation: 135

There are multiple possibilities that could cause this issue. The first thing you should check is that in your list, make sure you are using a reuse identifier for the cell prototype and that you are referencing it. Additionally, make sure you reload the table whenever you add an element (don't constantly do it as it will drain the user's battery). If neither of these are working, it's possible you didn't connect your outlets properly.

Upvotes: 2

David Steppenbeck
David Steppenbeck

Reputation: 1084

It's best to reload the table whenever your data source changes, which you can do like this:

var items: [String] = ["1", "2", "3"] {
    didSet {
        tableView.reloadData()
    }
}

func insertItem(){
    if let text = itemLbl.text { 
        items.append(itemLbl.text)
    }
}

Upvotes: 3

koen
koen

Reputation: 5729

Have you tried using tableView.reloadData() ? Also, do not force unwrap itemLabel.text.

func insertItem(){
    if let itemText = itemLabel.text {
       items.append(itemText)

       tableView.reloadData()
    }
}

Make sure to also add tableView.reloadData() at the end of viewDidLoad().

Upvotes: 0

Related Questions