開発メモ

開発関係のメモをいろいろと。たぶん。

TableViewのCellをスワイプしてコマンドを実行する方法のメモ

開発環境

環境 情報
Xcode 6.0.1 (6A317)
Swift 1.0
iOS 8.0
Date 2014/09/28

※iOS8以降専用

概要

通常の編集画面はこんな感じ。

f:id:see_ku:20140929084209p:plain

この画面も普通に使える上で、Cellをスワイプするとこんな感じになるようにする。

f:id:see_ku:20140929084223p:plain

実際の処理

Main.storyboard

自力でUITableViewを追加。あえて、UITableViewControllerは使わない。この時、AutoLayoutの設定をしておく必要がある。設定してない場合、Cellの移動やスワイプでのコマンド表示がおかしくなったり。

SwipeCellViewController.swift

システムに用意されたEditボタンを使う場合、編集モードの指定がsetEditingに来るので、これをoverrideして自分のTableViewに反映させる。

 override func setEditing(editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)

        swipeTable.setEditing(editing, animated: animated)
    }

iOS8から追加になった『tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?』を使って、スワイプで出てくるコマンドを設定。

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

        // 編集
        let edit = UITableViewRowAction(style: .Normal, title: "Edit") {
            (action, indexPath) in

            self.itemArray[indexPath.row] += "!!"
            self.swipeTable.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
        }

        edit.backgroundColor = UIColor.greenColor()

        // 削除
        let del = UITableViewRowAction(style: .Default, title: "Delete") {
            (action, indexPath) in

            self.itemArray.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }

        del.backgroundColor = UIColor.redColor()

        return [edit, del]
    }

あとは、編集操作に対応する関数を追加。

 func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }

    func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }

    func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
        let tmp = itemArray[sourceIndexPath.row]
        itemArray.removeAtIndex(sourceIndexPath.row)
        itemArray.insert(tmp, atIndex: destinationIndexPath.row)
    }

    // 編集操作に対応
    // ※スワイプで処理する場合、ここでは何もしないが関数は必要
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    }

なぜか『tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)』の実装が必要。特にすることはないので、中身は無しでok。たぶん。

参考資料

[iOS 8] UITableViewRowActionでセル編集機能をカスタマイズする | Developers.IO
http://dev.classmethod.jp/?p=111444

ソースコード

ソースコードはこちら。

See_Ku / SwipeCellTips — Bitbucket
https://bitbucket.org/See_Ku/swipecelltips