Emi Emi - 6 months ago 132
iOS Question

How to customize delete button in UITableView

I tried to customize my delete button in

UITableView
. I used a function but it didn't work because Xcode found an error. By the way I'm using custom cells in
UITableView
.

This is my code:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var myTableView: UITableView!


override func viewDidLoad() {
super.viewDidLoad()

}

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
let deleteButton = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action, indexPath) in
self.myTableView.dataSource?.tableView?(
self.myTableView,
commitEditingStyle: .Delete,
forRowAtIndexPath: indexPath
)

return
})

deleteButton.backgroundColor = UIColor.blackColor()

return [deleteButton]
}


}


And in this line is error:

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {


the erros is: Objective-C method 'tableView:editActionsForRowAtIndexPath:' provided by method 'tableView(:editActionsForRowAtIndexPath:)' conflicts with optional requirement method 'tableView(:editActionsForRowAtIndexPath:)' in protocol 'UITableViewDelegate'

So I want to change the text and background color. If there is any other method, like using icon and not text please show me, thanks.

Answer

The error is indicating that the function you defined with the same method signature as the one defined in UITableViewDelegate has different types that are not compatible. Specifically your return type needs to be [UITableViewRowAction]? instead of [AnyObject]?

Change:

    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

To:

    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?