SRMR
SRMR

Reputation: 3134

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    

Upvotes: 6

Views: 11431

Answers (2)

Mohit Kumar
Mohit Kumar

Reputation: 3086

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.

Upvotes: 8

Ilya  Lapan
Ilya Lapan

Reputation: 1103

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

Upvotes: 15

Related Questions