How to resort tableViewCell so when I click on any cell it will move to the top|beginning of the cell
Example cell
Java
PHP
CSS /clicked on/
HTML
SQL
Expected result
CSS
Java
PHP
HTML
SQL
CodePudding user response:
class ViewController: UITableViewController {
var languages = [
"CSS",
"Java",
"PHP",
"HTML",
"SQL"
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return languages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = languages[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
languages.insert(languages.remove(at: indexPath.row), at: 0)
tableView.beginUpdates()
tableView.moveRow(at: indexPath, to: [0, 0])
tableView.endUpdates()
}
}

