xNightxOwl
xNightxOwl

Reputation: 538

In IOS, while in "Edit Mode", how do I add a new section with cell to a static UITableView?

It appears I have hit a dead end trying to figure this out.

I'm working on an app that contains a static UITableView with 3 sections, each section containing one cell. Each cell contains a UITextField. On the navigation bar, I have an edit button, once clicked the UITextFields are enabled--allowing the user to modify the text.

I was wondering if someone could guide me on the right direction. I want to add an extra section with one cell, containing a "Delete" button.

The best example I could find for what I am trying to do is in the Contacts app. Notice here, there's no delete button.Regular view, no delete button

Once edit mode is enabled, an extra section with cell is added, which holds a delete button. edit mode, delete button appears

I have already setup the code to enable edit mode by overriding the setEditing method.

override func setEditing(editing: Bool, animated: Bool) {

    super.setEditing(editing, animated: animated)

    if editing {
        // enable textfields
    }
    else {
       // disable textfields 
       // save data
    }

Thanks in advance! :)

Upvotes: 0

Views: 920

Answers (1)

Aaron Wojnowski
Aaron Wojnowski

Reputation: 6480

When you enable or disable editing, reload your table view:

self.tableView!.reloadData()

From there, you can return some different values depending on whether you're editing or not. Here's some examples:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    var sectionCount = 1
    if tableView.editing {

        sectionCount += 1

    }
    return sectionCount

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let lastSection = 1
    if section == lastSection {

        return 1

    }
    return 5

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let lastSection = 1
    if (indexPath.section == lastSection) {

        // return the special delete cell

    } else {

        // return other cells

    }

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let lastSection = 1
    if (indexPath.section == lastSection) {

        // handle delete cell

    } else {

        // handle other cells

    }

}

Upvotes: 2

Related Questions