0

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)
1
  • since you are return wInstockArray.count + 1it will get index out of range . For count +1 you should return empty cell Commented Mar 19, 2018 at 6:50

2 Answers 2

1

Inside button click method, please reload your table.

YOUR_TABLE.reloadData()

and update this method,

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return wInstockArray.count
}
Sign up to request clarification or add additional context in comments.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.