Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView setContentOffset:animated not working in iOS11

I added a method to make the scroll view to scroll to top of it. This is working as expected in iOS10. But when I upgraded to iOS11 with Xcode 9, it is not working. Is there anything that am missing respective to iOS11.
Below code was working:

[self setContentOffset:CGPointZero animated:YES];

Updating question after comment from OP (UPDATE)

I find the reason why setContentOffset:animated is not working, I use UITableView and I make some custom cell in my tableview, tableview has a property "estimatedRowHeight" , we should make this property equal "0", I guess when iOS11 calculate it's content size it will use "estimatedRowHeight", if we don't set this property , it will use system default.

This is very useful and should be more visible

like image 867
Jason Liu Avatar asked Oct 10 '17 06:10

Jason Liu


Video Answer


4 Answers

Try this

if tableView.numberOfRows(inSection: 0) > 0 {
    tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
}
like image 135
mishimay Avatar answered Sep 28 '22 06:09

mishimay


You have to do

self.view.layoutIfNeeded()

before setContentOffset. It updates the contentSize of UIScrollView and then contentOffset is available.

like image 20
Yusuke Avatar answered Sep 28 '22 05:09

Yusuke


Setting estimatedRowHeight = 0, estimatedSectionHeaderHeight = 0, estimatedSectionFooterHeight = 0 for the scrollview solved the issue. whenever the content offset is changed, the heights of rows, header and footers of each section is calculated by the UIKit to scroll to the new offset. estimatedRowHeight, estimatedSectionHeaderHeight, estimatedSectionFooterHeight will be -1 by default

like image 35
Rahamaan Sherif Avatar answered Sep 28 '22 05:09

Rahamaan Sherif


(SWIFT 4) I had a similar problem, the problem was the animated : true. So, you can try by doing this manually:

view.layoutIfNeeded()
UIView.animate(withDuration: 0.2) {
   self.scroll.setContentOffset(.zero, animated: false)
}

Hope it helps. It fixed for me

like image 43
Pablo Blanco Avatar answered Sep 28 '22 05:09

Pablo Blanco