Search code examples
iosswiftuitableviewnsarray

Retrieving the values of array in table view cell swift ios


I am trying to retrieve the values of wInstockArray in a table view cell. Currently the the wInstockArray is empty I am inserting a string on a button click and appending in array. but when I retried the values in cellForRowAtIndexath method it gives error

Index out of range

What I have defined is :

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return wInstockArray.count + 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let firstCell = firstTableView.dequeueReusableCell(withIdentifier: "firstCell")! as UITableViewCell
    if wInstockArray.count == 0 {
        print("no widgets in instock")
    } else {
        firstCell.textLabel?.text = wInstockArray[indexPath.row]
        print("\(wInstockArray.count)")  //prints 1
        return firstCell
    }
}

inside button click action

wInstockArray.append(item)

Solution

  • In numberOfRowsInSection method return wInstockArray array count

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
      return wInstockArray.count
    }
    

    Inside the button click action, reload the tableView

    wInstockArray.append(item)
    tableView.reloadData()