UITableView編輯模式

UITableView有兩種模式,普通模式和編輯模式。在編輯模式下可以對cell進行排序、刪除、插入等等。

  1. 如何進入編輯模式
    調用tableView的setEditing(editing: Bool, animated: Bool)方法。
  • 進入編輯模式以后發生了什么
    • 向每個cell發送setEditing:animated:方法
  • 進入編輯模式以后cell的變化
    普通模式

    編輯模式

    普通模式下cell的contentview的bounds就是cell的bounds。
    編輯模式下,cell有三部分組成,左邊的Editing control,中間的contentview,右邊的reordering control。這時contentview的位置和大小都發生了變化。
    所以一般情況下,把需要展示的東西加到contentview上,而不是cell上。文檔是也有說明。

The content view of a UITableViewCell object is the default superview for content displayed by the cell. If you want to customize cells by simply adding additional views, you should add them to the content view so they will be positioned appropriately as the cell transitions into and out of editing mode

  • 刪除模式
    • 指定模式為刪除模式
    func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        return .Delete
    }
  • 定制刪除提示語
    func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
        return "我刪除啦"
    }

這時,cell右側又多出來一個部分,叫做UITableViewCellDeleteConfirmtionView,不同的刪除提示語,長度不一樣。

確認刪除態的cell

刪除

  • 插入模式
    • 將style設為insert就好
    func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        return .Insert
    }
  • 展示右邊的排序按鈕
    func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
    //do something    
    }

實現這個方法就好,即使什么都不做


  • 展示多選按鈕
        tableView?.allowsMultipleSelectionDuringEditing = true
        tableView?.tintColor = UIColor.blackColor()
多選及小對勾
  • swipe to delete
    • 實現相應的代理方法
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {   
    }

這個方法里不能調用setEditing(_:animated:)方法

  • tableView(_:editingStyleForRowAt:)方法必須返回delete
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容