I have a table view inside a UIViewController with editing enabled for deleting rows. Swiping from the right lets me delete rows and I have the edit button on the navigation bar but it doesn't actually do anything except switch from saying Edit to Done.
Here is how I'm creating my table view.
override func viewWillAppear(animated: Bool) {
for view in self.view.subviews {
view.removeFromSuperview()
}
if sharedCart.shoppingCart.isEmpty {
self.navigationItem.rightBarButtonItem = nil
isEmptyLabel = UILabel(frame: CGRectMake(self.view.frame.width / 2, self.view.frame.height / 2, self.view.frame.width, self.view.frame.height))
isEmptyLabel.center = self.view.center
isEmptyLabel.text = "Your cart is empty."
isEmptyLabel.textAlignment = .Center
isEmptyLabel.textColor = UIColor.whiteColor()
isEmptyLabel.font = UIFont(name: "Helvetica-Light", size: 20.0)
self.view.addSubview(isEmptyLabel)
} else {
isEmptyLabel.removeFromSuperview()
total = 0
let editItem = self.editButtonItem()
self.navigationItem.rightBarButtonItem = editItem
tableView = UITableView(frame: self.view.frame, style: .Grouped)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.clearColor()
tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
tableView.registerNib(UINib(nibName: "CartCell", bundle: nil), forCellReuseIdentifier: "passCartCell")
tableView.registerNib(UINib(nibName: "CartFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: "cartFooter")
self.view.addSubview(tableView)
}
And I use these methods for editing.
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
sharedCart.shoppingCart.removeAtIndex(indexPath.row)
self.viewWillAppear(true)
}
}
Cedric Michael's answer almost works, but it disables editButtonItem's automatic, animated toggling between the Edit and Done title & associated state. The better fix is this:
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: animated)
}
Also, if you want to hide the Edit button for an empty shopping cart, it would be better form to set navigationItem.rightBarButtonItem = editButtonItem in viewDidLoad() and simply set navigationItem.rightBarButtonItem.isHidden to true or false in viewWillAppear() according to the shopping cart.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With