Laroms
Laroms

Reputation: 85

How do I get my 'Edit' button turn into 'Done' while editing?

I've read a few posts, but do not see how to implement it in my own code. I've got a bar button item (Edit) which I dragged from the object library; it does the job, but I would like it to display 'Done' whilst in editing mode - any help will be much appreciated. My code looks like this:

@IBAction func editButton(sender: AnyObject) {
    self.editing = !self.editing {

// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}



// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {

        // Delete the row from the data source
        lessons.removeAtIndex(indexPath.row)
        saveLessons()
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

    } else if editingStyle == .Insert {

        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}


// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    let itemToMove = lessons[fromIndexPath.row]

    lessons.removeAtIndex(fromIndexPath.row)

    lessons.insert(itemToMove, atIndex: toIndexPath.row)

    saveLessons()

}

Upvotes: 1

Views: 85

Answers (1)

vadian
vadian

Reputation: 285082

Override setEditing

override func setEditing(editing: Bool, animated: Bool) {
   super.setEditing(editing, animated:animated)
   if editing == true {
     // set title of the bar button to 'Done'
     editBarButton.title = "Done"      
   } else {
     // set title of the bar button to 'Edit'
     editBarButton.title = "Edit"
   }
}

or shorter using the Ternary Conditional Operator

override func setEditing(editing: Bool, animated: Bool) {
   super.setEditing(editing, animated:animated)
   editBarButton.title = editing ? "Done" : "Edit"
}

Upvotes: 2

Related Questions