今回の内容
コードと簡単解説
-
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {}
でcellを並び替える事を可能にするかをtrue
またはfalse
で設定します。 -
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {}
で、cellを並び替えるときに働かせる処理を設定します。 -
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {}
でcellの左側に表示する内容を設定します。今回は、.none
で何も表示しないようにしています。 -
editingStyleForRowAt
を.none
で設定した事によって残ってしまった空白を削除する為に、func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {}
をfalse
で設定します。
import UIKit
class ViewController: UIViewController {
let tableView = UITableView()
var cellContentsArray = ["UIKit","SwiftUI","MapKit","ARKit","CoreML","WebKit","Foundation","LocalAuthentication","CoreGraphics","Combine"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.frame = CGRect(x: view.frame.minX, y: view.frame.minY, width: view.frame.width, height: view.frame.height)
tableView.isEditing = true
view.addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
}
}
extension ViewController:UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellContentsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = cellContentsArray[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 cellContent = cellContentsArray[sourceIndexPath.row]
cellContentsArray.remove(at: sourceIndexPath.row)
cellContentsArray.insert(cellContent, at: destinationIndexPath.row)
}
}
extension ViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
}
終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。