[swift] tableViewに削除機能を実装

目次

tableViewに削除機能を実装

削除ボタンを配置

StoryBoardでNavigationBar上にBarButtonItemを配置

IBActionを定義

@IBAction func tapEdit(sender: AnyObject) {
        if editing {
            super.setEditing(false, animated: true)
            tableView.setEditing(false, animated: true)
        } else {
            super.setEditing(true, animated: true)
            tableView.setEditing(true, animated: true)
        }
    }

*これでボタンを押すとTableViewのセルが削除できるモードに切り替えることができる
*削除モードを解除するにはもう一度ボタンを押せばよいようになっている

削除ボタンPush時の挙動

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        // 削除のとき.
        if editingStyle == UITableViewCellEditingStyle.Delete {
            // 指定されたセルのオブジェクトをmyItemsから削除する.
            myItems.removeAtIndex(indexPath.row)
            // TableViewを再読み込み.
            tableView.reloadData()
        }
    }

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です