facebook twitter hatena line email

Ios/swift/TableView/削除並替処理

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
   @IBOutlet weak var tagTableView: UITableView!
   private var _tags: Array<String> = ["タイトル1", "タイトル2", "タイトル3"]
   override func viewDidLoad() {
       super.viewDidLoad()
       let rightBarButtonItem: UIBarButtonItem = editButtonItem()
       self.navigationItem.setRightBarButtonItems([rightBarButtonItem], animated: true)
   }
   override func setEditing(editing: Bool, animated: Bool) {
       super.setEditing(editing, animated: animated)
       tagTableView.editing = editing
   }
   // 削除可能判定
   func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
       return true
   }
   // 削除処理
   func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
       _tags.removeAtIndex(indexPath.row)
       tagTableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: 0)],
                                        withRowAnimation: UITableViewRowAnimation.Fade)
   }
   // 並び替え可能判定
   func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
       return true
   }
   // 並び替え処理
   func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
       let targetTitle = _tags[sourceIndexPath.row]
       if let index = _tags.indexOf(targetTitle) {
           _tags.removeAtIndex(index)
           _tags.insert(targetTitle, atIndex: destinationIndexPath.row)
       }
   }

参考:http://himaratsu.hatenablog.com/entry/tableview/editmode