import UIKit
class ViewController: UIViewController {
var dataArray = ["1", "2", "3", "4", "5", "6"]
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// tableViewの編集を可能にする
tableView.isEditing = true
tableView.allowsMultipleSelectionDuringEditing = true
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel!.text = dataArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let removeElement = dataArray.remove(at: sourceIndexPath.row)
dataArray.insert(removeElement, at: destinationIndexPath.row)
// リロード前に選択済セルを取得
let indexPaths = tableView.indexPathsForSelectedRows
// リロード
tableView.reloadData()
// 選択済セルを復元
indexPaths?.forEach {
tableView.selectRow(at: $0, animated: false, scrollPosition: .none)
}
}
}
Last active
July 24, 2018 00:04
-
-
Save KentarouKanno/8c75ba9767db85056f54695522c8440d to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment