データはArray
になっていますが中身がDictionary
なのでちょっと工夫が必要ですね。
検証したコードは以下になります。
データの構造はシンプルなものなのでご自身が定義しているものに置換えて使用してください。
swift
1
2import UIKit
3
4class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
5
6 @IBOutlet weak var tableView: UITableView!
7 var items: [Dictionary<String, String>] = []
8
9 override func viewDidLoad() {
10 super.viewDidLoad()
11
12 items = [["title": "a"], ["title": "b"], ["title": "c"], ["title": "d"], ["title": "e"], ["title": "f"]]
13
14 tableView.estimatedRowHeight = 20
15 tableView.rowHeight = UITableViewAutomaticDimension
16
17 navigationItem.leftBarButtonItem = editButtonItem
18 }
19
20 override func setEditing(_ editing: Bool, animated: Bool) {
21 super.setEditing(editing, animated: animated)
22 tableView.isEditing = editing
23 }
24
25 func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
26 return true
27 }
28
29 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
30
31 let target = items[sourceIndexPath.row]
32 let targetTitle = items[sourceIndexPath.row]["title"]!
33 if let index = items.index(where: { $0["title"] == targetTitle }) {
34
35 items.remove(at: index)
36 items.insert(target, at: destinationIndexPath.row)
37 }
38 }
39
40
41 // MARK: - TableView Delegate & DataSource
42
43 // Row Count
44 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
45 return items.count
46 }
47
48 // Generate Cell
49 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
50 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
51 cell.textLabel?.text = items[indexPath.row]["title"]
52 return cell
53 }
54
55 // Select Cell
56 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
57 tableView.deselectRow(at: indexPath as IndexPath, animated: true)
58 print("Cell Tap - ",indexPath.row)
59 }
60}