How can I Insert multiple rows into a tableview

I have a label and a button whenever I click the button I want to create new rows and insert them directly below the clicked button . I can do it successfully when adding 1 element but if I had 2 or more elements I get this error

Thread 1: Exception: "Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)."

["Snapchat","Tik Tok"] Gives me an error
["Snapchat"] That does not

class ExpandController: UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var TableSource: UITableView!


var videos: [String] = ["FaceBook","Twitter","Instagram"]

override func viewDidLoad() {
    super.viewDidLoad()
    TableSource.delegate = self
    TableSource.dataSource = self
    TableSource.tableFooterView = UIView(frame: CGRect.zero)
    // Do any additional setup after loading the view.
}



@IBAction func RowClick(_ sender: UIButton) {
    guard let cell = sender.superview?.superview as? ExpandTVC else {
        return
    }

    let indexPath = TableSource.indexPath(for: cell)
    
    InsertVideoTitles(indexPath: indexPath)
}

func InsertVideoTitles(indexPath: IndexPath?)
{
    
    let targetRow = indexPath!.row < videos.endIndex ? indexPath!.row + 1 : indexPath!.row
    let data = ["Snapchat","Tik Tok"]
    videos.insert(contentsOf: data, at: targetRow)
    let newIndexPath = IndexPath(row: targetRow, section: 0)
    TableSource.beginUpdates()
    TableSource.insertRows(at: [newIndexPath], with: .automatic)
    TableSource.endUpdates()
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let videoTitle = videos[indexPath.row]
    let cell = TableSource.dequeueReusableCell(withIdentifier: "ExpandTVC") as! ExpandTVC
    cell.Title.text = videoTitle
    
    cell.ButtonRow.tag = indexPath.row
    cell.ButtonRow.setTitle("Rows",for: .normal)
    
    return cell
}

}

any suggestions would be great

This is kind of off-topic for this forum, whose purpose is to discuss the swift language. Your question is about UIKit, which is an Apple technology. See Stack Overflow and the Apple dev forums.

Having said that, you insert two rows into your videos list but only insert one row into the tableView. That's what the error message says. 3 + 1 != 5.

1 Like