📖
【Swift】Move TableView Cells【コピペコード】
【「ViewController」のコード】
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var models = [
"first",
"second",
"third",
"fourth"
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = models[indexPath.row]
cell.textLabel?.font = UIFont(name: "Arial", size: 22)
return cell
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
models.swapAt(sourceIndexPath.row, destinationIndexPath.row)
}
@IBAction func didTapSort() {
if tableView.isEditing {
tableView.isEditing = false
} else {
tableView.isEditing = true
}
}
}
参考動画
Move TableView Cells in Swift 5 (Xcode 11) | 2020
Discussion