Mohammed Riyadh
Mohammed Riyadh

Reputation: 1019

UITableView scroll to selected cell after navigation

I have a table View that fetching remote data from backend which is all working fine, what i'm trying to accomplish is when user click on any cell to navigate to other ViewController (details controller) and when press the back button the table view should scroll to the selected cell and not to go back to top i'v tried tableView.scrollToRow as shown below but its not working? i know that i'm calling tableView.reloadData() in my loading data function other wise it won't load

class feeds: UITableViewController {
    var data = [AnyObject]()
    override func viewDidLoad() {
        super.viewDidLoad()

        LoadData()
    }


    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return data.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

       // configur tabl cell

        return cell
    }

    func LoadData(){

    // Fetch Feeds to dataArray 
        // Reload UITable View
        self.tableView.reloadData()
        let celloffset = UserDefaults.standard.integer(forKey: "celloffset")
        if celloffset != 0{
        let index = IndexPath(item: celloffset, section: 0)
        self.tableView.scrollToRow(at: index, at: UITableViewScrollPosition.middle, animated: false)
        }
    }


    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UserDefaults.standard.set(indexPath.row, forKey: "celloffset")

        // Navigate to Details VC
    }

}

Any help or ideas will be much appreciated

Upvotes: 0

Views: 1902

Answers (2)

pkc
pkc

Reputation: 8506

When you are coming back to initial view controller, then you don't need to fetch data again. Simply use ViewWillAppear method. Get the celloffset and scroll table view.

let celloffset = UserDefaults.standard.integer(forKey: "celloffset")
if celloffset != 0{
let index = IndexPath(item: celloffset, section: 0)
self.tableView.scrollToRow(at: index, at: UITableViewScrollPosition.middle, animated: false)}

Upvotes: 3

Jože Ws
Jože Ws

Reputation: 1814

viewDidLoad is only called once upon view controller initialization, not when popping view controllers on navigation stack. Call LoadData() in viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
    LoadData()
}

Upvotes: 1

Related Questions