Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to Table View Header top

I have a UITableView header that takes up the full frame of the screen.

Every time the app goes in the background, and then comes back into the foreground/active, I would like the screen to be set back to the header top.

I've only seen answers having to do with scrolling to the top of the table with something like these answers that use something like self.tableView.scrollToRow(at: top, at: .top, animated: true), but that doesn't work because it only scrolls back to Section 0 Row 0 of the UITableView not the top of the header of the UITableView.

Any ideas?

Thanks!

Edit: Tried this

override func viewWillAppear(_ animated: Bool) {
    self.tableView.setContentOffset( CGPoint(x: 0, y: 0) , animated: true)
}

And here is some noteworthy table setup code:

// Set up Frames
let headerFrame: CGRect = UIScreen.main.bounds
// Background Table
self.tableView.isPagingEnabled = true

// Set up Table Header
let header = UIView(frame: headerFrame)
self.tableView.tableHeaderView = header    
like image 787
SRMR Avatar asked Dec 02 '22 14:12

SRMR


2 Answers

TableView is a scroll view subclass, so I imagine this should work:

 self.tableView.setContentOffset( CGPoint(x: 0, y: 0) , animated: true)

ViewWillAppear does not get called when app enters foreground. Register you VC for UIApplicationWillEnterForegroundNotification

like image 64
Ilya Lapan Avatar answered Dec 05 '22 03:12

Ilya Lapan


You can scroll to Section Header, try following code:

DispatchQueue.main.async {
    let indexPath = IndexPath(row: NSNotFound, section: yourSectionIndex)
    self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}

For Row add: NSNotFound

Change .top/.bottom in "scrollToRow" as per your requirement.

like image 21
Mohit Kumar Avatar answered Dec 05 '22 03:12

Mohit Kumar