I'm trying that when I use close an app and start it again a tableview put the last cell pressed on the top. I'm able to store the last cell position with the next code and even move to the top position when press the cell. But I don't now how force the table move to that position when the user comes back.The table has only one section. I'm reading several posts but I don't know how to adapt the solution to my code. Please help! My code is:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UserDefaults.standard.set(indexPath.row, forKey: "celdaPulsada")
let celdaPulsada = UserDefaults.standard.integer(forKey: "celdaPulsada")
tableView.beginUpdates()
tableView.moveRow(at:[0,celdaPulsada], to: [0, 0])
tableView.endUpdates()
}
CodePudding user response:
This is the demo code please modify it according to your requirement
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
scrollTableViewToLastSelectedPosition()
}
private func setupView() {
tableView.dataSource = self
tableView.delegate = self
}
private func scrollTableViewToLastSelectedPosition() {
let celdaPulsada = UserDefaults.standard.integer(forKey: "celdaPulsada")
tableView.scrollToRow(at: IndexPath(row: celdaPulsada, section: 0), at: .top, animated: false)
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Cell No \(indexPath.row 1)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UserDefaults.standard.set(indexPath.row, forKey: "celdaPulsada")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
}