Search code examples
swiftxcodeinserttableviewsections

insert new section with UIButton (or Bar button) in Xcode using swift


In Xcode (using swift) I have a tableView with 3 sections. I want the insert a new section when the user taps a button, with the title for the section being fed in from a textField (the textField is not in the tableView)

I am familiar with the tableView.insertrow(just pass in correct indexPath), but I don't know how to use tableView.insertSection (which requires an indexSet).

I'm using a 2d array to populate the table View.

var twoDArray = [
["apple", "banana", "pear"],
["carrot", "broccoli"],
["chicken", "beef"]
]

currently the titles for my headers are stored in a separate array:

var sections = ["Fruits", "Veggies", "Meats"]

How can I insert a new section with input from textField.text when the user taps the button using tableView.insertSection (ideally, I would like to do this without reloading the entire tableView)


Solution

  • If you need to add a 4th section and animate the section insertion you could do something like this:

    var twoDArray = [
    ["apple", "banana", "pear"],
    ["carrot", "broccoli"],
    ["chicken", "beef"]
    ]
    
    var sections = ["Fruits", "Veggies", "Meats"]
    
    //After user presses the button
    sections.append("Candy")
    twoDArray.append(["Chocolate", "Pure Sugar"])
    
    self.tableView.insertSections(IndexSet(integer: sections.count - 1), with: .automatic)
    

    You just need to make sure your datasource arrays are set prior to calling insertSections or you will crash with an error letting you know that your section insertion needs to match your source insertion.