CodingTour
iOS8 用UITableViewRowAction实现Cell自定义滑动操作

在iOS 8以前,如果想自定义一个UITableViewCell的滑动操作是一件比较麻烦的事情,系统只支持删除,如果我们想加上一个类似于“置顶”的操作需要处理不少逻辑,而进入iOS 8以后,系统提供了UITableViewRowAction以及新的delegate方法,使得自定义一些操作变得非常容易,如果想加上一个置顶,只需要这样:

 

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

    let topAction = UITableViewRowAction(style: .Default, title: "置顶") {

        (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in

        tableView.editing = false

    }

    return [topAction]

}

 

在这里可以添加任意多个操作。要确保这个代码生效,还是需要实现commitEditingStyle这个delegate方法,哪怕里面什么也不处理: 

 

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

 

}