Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll immediately to row in table before view shows

A view with a table gets pushed onto the screen and I want it to scroll to a certain row in the table before the screen actually displays. I use this code within the final viewcontroller.

NSIndexPath *scrollToPath = [NSIndexPath indexPathForRow:5 inSection:0]; 
[theTable scrollToRowAtIndexPath:scrollToPath atScrollPosition:UITableViewScrollPositionTop animated:NO];

When I put it in viewDiDAppear method, then it briefly flashes from the intial position of the table (at the top) to the row I want. I don't want it to show the initial position. If I put it in viewDidLoad or viewWillAppear then it crashes with a NSRangeException, presumably because the table isn't set up yet.

How would I get it to scroll without showing the initial position?

like image 949
cannyboy Avatar asked May 28 '10 20:05

cannyboy


1 Answers

Needs to scroll to cell before table view appears on the screen, but after table view loads data. Use this in the viewDidLoad doesn't work for me.

This code works well to me:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    DispatchQueue.main.async { [weak self]
        let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
        self?.tableView.scrollToRow(at: indexPath, at: .middle, animated: false)
    }
}

Tested on iOS 14.1.

It works in viewDidAppear even without DispatchQueue.main.async but scrolling become visible to users. It is not a good option I think.

like image 58
Andrew Bogaevskyi Avatar answered Oct 05 '22 17:10

Andrew Bogaevskyi