回答編集履歴
1
中央値を取る方法
answer
CHANGED
@@ -8,4 +8,79 @@
|
|
8
8
|
[id: 3, order: 1, name: "キジ"],
|
9
9
|
[id: 4, order: 3, name: "トラ"]
|
10
10
|
]
|
11
|
-
```
|
11
|
+
```
|
12
|
+
|
13
|
+
# 中央値を取る方法
|
14
|
+
|
15
|
+
Swift2の丸投げコードです。
|
16
|
+
セルはRight Detailで。
|
17
|
+
|
18
|
+
```swift
|
19
|
+
class TableViewController: UITableViewController {
|
20
|
+
|
21
|
+
var array = [
|
22
|
+
["id": 0, "order": 2.0, "name": "猫"],
|
23
|
+
["id": 1, "order": 0.0, "name": "犬"],
|
24
|
+
["id": 2, "order": 4.0, "name": "猿"],
|
25
|
+
["id": 3, "order": 1.0, "name": "キジ"],
|
26
|
+
["id": 4, "order": 3.0, "name": "トラ"],
|
27
|
+
]
|
28
|
+
|
29
|
+
override func viewDidLoad() {
|
30
|
+
super.viewDidLoad()
|
31
|
+
self.navigationItem.rightBarButtonItem = self.editButtonItem()
|
32
|
+
self.sortArray()
|
33
|
+
}
|
34
|
+
|
35
|
+
func sortArray() {
|
36
|
+
array = array.sort{($0["order"] as! Double) < ($1["order"] as! Double)}
|
37
|
+
}
|
38
|
+
|
39
|
+
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
40
|
+
return array.count
|
41
|
+
}
|
42
|
+
|
43
|
+
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
|
44
|
+
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
|
45
|
+
let obj = array[indexPath.row]
|
46
|
+
cell.detailTextLabel!.text = "\(obj["order"]!)"
|
47
|
+
cell.textLabel!.text = obj["name"] as? String
|
48
|
+
return cell
|
49
|
+
}
|
50
|
+
|
51
|
+
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
|
52
|
+
|
53
|
+
print("from \(fromIndexPath.row) to \(toIndexPath.row)")
|
54
|
+
|
55
|
+
if fromIndexPath.row == toIndexPath.row {
|
56
|
+
print("skip")
|
57
|
+
} else {
|
58
|
+
var newOrder: Double
|
59
|
+
if toIndexPath.row == 0 {
|
60
|
+
//一番上に移動した場合は先頭セル - 1
|
61
|
+
newOrder = (array[toIndexPath.row]["order"] as! Double) - 1.0
|
62
|
+
} else if toIndexPath.row == array.count - 1 {
|
63
|
+
//一番下に移動した場合は末尾セル + 1
|
64
|
+
newOrder = (array[toIndexPath.row]["order"] as! Double) + 1.0
|
65
|
+
} else {
|
66
|
+
//途中に移動したときは上下セルの中央値
|
67
|
+
var rowPrev: Int, rowNext: Int;
|
68
|
+
if (toIndexPath.row < fromIndexPath.row) {
|
69
|
+
//上に移動した場合
|
70
|
+
rowPrev = toIndexPath.row - 1
|
71
|
+
rowNext = toIndexPath.row
|
72
|
+
} else {
|
73
|
+
//下に移動した場合
|
74
|
+
rowPrev = toIndexPath.row
|
75
|
+
rowNext = toIndexPath.row + 1
|
76
|
+
}
|
77
|
+
newOrder = ((array[rowPrev]["order"] as! Double) + (array[rowNext]["order"] as! Double)) / 2.0
|
78
|
+
}
|
79
|
+
array[fromIndexPath.row]["order"] = newOrder
|
80
|
+
|
81
|
+
self.sortArray()
|
82
|
+
tableView.reloadData()
|
83
|
+
}
|
84
|
+
}
|
85
|
+
}
|
86
|
+
```
|