Posted at

Swift3 - UITableView並び替え

More than 1 year has passed since last update.


参考

https://github.com/himaratsu/TableViewEditSample/blob/master/TableViewEditSample/ViewController.swift

myItemsはArray


実装

// (5) 移動を有効
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

// (6) 移動時の処理
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

// データの順番を整える
let targetTitle = myItems[sourceIndexPath.row]
if let index = myItems.index(of: targetTitle) {
myItems.remove(at: index)
myItems.insert(targetTitle, at: destinationIndexPath.row)
print(myItems)
}
}

private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
print(myItems,

[indexPath.row])
}