Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set table view into editing mode

I have a UITableView in a UIViewController and have added an edit button from code rather than IB. This comes with UITableViewControllers but not UIVCs. How can I get this button to put the table view into editing mode in swift? Thanks in advance for any help.

class WordsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate  {
  override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = self.editButtonItem()
  }

  func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
  }
}
like image 700
richc Avatar asked Dec 08 '15 13:12

richc


2 Answers

Here is a solution for Swift 4.2:

override func viewDidLoad() {
  super.viewDidLoad()

  // Use the edit button provided by the view controller.
  navigationItem.rightBarButtonItem = editButtonItem
}

override func setEditing(_ editing: Bool, animated: Bool) {
    // Takes care of toggling the button's title.
    super.setEditing(editing, animated: true)

    // Toggle table view editing.
    tableView.setEditing(editing, animated: true)
}

The view controller's setEditing is called by default when the editButtonItem is pressed. By default, pressing the button toggles its title between "Edit" and "Done", so calling super.setEditing takes care of that for us, and we use the tableView's setEditing method to toggle the editing state of the table view.

Sources:

  • https://developer.apple.com/documentation/uikit/uiviewcontroller/1621471-editbuttonitem
  • https://developer.apple.com/documentation/uikit/uiviewcontroller/1621378-setediting
  • https://developer.apple.com/documentation/uikit/uitableview/1614876-setediting
like image 145
Jared Cleghorn Avatar answered Sep 20 '22 14:09

Jared Cleghorn


Create rightBarButtonItem as below with an action.

In viewDidLoad() :

let rightButton = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("showEditing:"))
    self.navigationItem.rightBarButtonItem = rightButton

and then make a function like,

 func showEditing(sender: UIBarButtonItem)
 {
    if(self.tableView.isEditing == true)
    {
        self.tableView.isEditing = false
        self.navigationItem.rightBarButtonItem?.title = "Done"   
    }
    else
    {
        self.tableView.isEditing = true
        self.navigationItem.rightBarButtonItem?.title = "Edit" 
    }
}

Make sure, : is appended to function name in Selector of action in viewDidLoad
Hope it helps!

like image 39
iRiziya Avatar answered Sep 21 '22 14:09

iRiziya