Brand0n_
Brand0n_

Reputation: 31

How can I reload a table view? Xcode 11

I am currently trying to add a row into the tableView, My code to add the view is as follows

     @IBAction func done(segue:UIStoryboardSegue) {
        let newContact = segue.source as! NewContactViewController
        FirstName = newContact.firstName
        LastName = newContact.lastName
           print("Adding the name: " + FirstName + " " + LastName + " to the nameArry")
        nameArry.append(FirstName + " " + LastName)
        print("Added " + nameArry[nameArry.count - 1] + " to name array")
        
        let indexPath = IndexPath(row: myContact.count + contacts.count - 1, section: 0) // Set the indexPath to the lowest part of the array
        
        tableView.beginUpdates() // Starts the update
        tableView.insertRows(at: [indexPath], with: .automatic) // Insert row at the lowest part of the table
        tableView.endUpdates() // Ends the update
        
        newContact.firstName = "" // Clears the variable "firstName"
        newContact.lastName = "" // Clears the variable "lastName"
        view.endEditing(true) // Disables Editing, saw it on youtube.
    }

I used myContact.count + contacts.count for the indexPath because thats what I use on my tableView

    // Get Number of items in table
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (myContact.count + contacts.count)
    }

I get the following error:

Thread 1: Exception: "attempt to insert row 4 into section 0, but there are only 4 rows in section 0 after the update" 

Upvotes: 0

Views: 116

Answers (2)

Brand0n_
Brand0n_

Reputation: 31

I figured it out, I wasn't getting the accurate count, since I wasn't appending anything to the contacts array.

contacts.append(Contacts(MyContact: nameArry[nameArry.count - 1], Me: ""))

let indexPath = IndexPath(row: myContact.count + contacts.count - 1, section: 0)

Upvotes: 0

Jawad Ali
Jawad Ali

Reputation: 14397

why are you removing one?

let indexPath = IndexPath(row: myContact.count + contacts.count - 1, section: 0) 

.... write this line without subtracting 1 like this ...

let indexPath = IndexPath(row: myContact.count + contacts.count , section: 0)

because if you are adding one row and subtracting it from total ... then The number of rows contained in an existing section after the update are equal to the number of rows contained in that section before the update

Upvotes: 2

Related Questions