Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setContentOffset on UIScrollView the right way

I'm using this code to scroll my UIScrollView down because I'm adding a new UIView on it from the bottom and I want to scroll down to it. I do it like this:

CGPoint newOffset = CGPointMake(mainScrollView.contentOffset.x, mainScrollView.contentOffset.y + floorf(bottomAttachmentView.frame.size.height / bottomAttachmentView.multFactor));
[mainScrollView setContentOffset:newOffset animated:YES];

I basically add my new element's height to the y of UIScrollView's contentOffset but sometimes it scrolls out of the scrollView contentSize, lower, that it is possible to scroll. It happens because I modify the contentSize before calling the method above and the height of the Scroll View shrinks.

How do you call the setContentOffset so it wouldn't make my scrollView scroll out of it's own contentSize? Thanks!

like image 382
Sergey Grischyov Avatar asked Mar 01 '13 13:03

Sergey Grischyov


2 Answers

All I had to do actually, was scroll my UIScrollView to the bottom like this:

CGPoint bottomOffset = CGPointMake(0, [mainScrollView contentSize].height - mainScrollView.frame.size.height);
[mainScrollView setContentOffset:bottomOffset animated:YES];
like image 70
Sergey Grischyov Avatar answered Sep 19 '22 03:09

Sergey Grischyov


You can also use this to scroll to bottom of scrollView (Swift 4)

let targetRect = CGRect(x: 0, y: mainScrollView.contentSize.height, width: 1, height: 1)
scrollView.scrollRectToVisible(targetRect, animated: true)
like image 42
ergunkocak Avatar answered Sep 20 '22 03:09

ergunkocak