Reputation: 2633
I am dynamically adding some views in scrollview and increasing the contentsize of scrollview too but I want to scroll the scrollview at the bottom of its height.
scrollRectToVisible is not helpful to me. It just scrolls to visible view of my iphone screen but I want to reach the bottom of contentsize of scrollview.
Can anyone give me some sample code?
Thanks,
Naveed Butt
Upvotes: 1
Views: 11797
Reputation: 37587
This is more reliable
CGSize contentSize = scrollview.contentSize;
[scrollview scrollRectToVisible: CGRectMake(0.0,
contentSize.height - 1.0,
contentSize.width,
1.0)
animated: YES];
Upvotes: -1
Reputation: 9540
In case, if you want the Swift version:
scrollView.setContentOffset(CGPointMake(0, max(scrollView.contentSize.height - scrollView.bounds.size.height, 0) ), animated: true)
Hope this helps!
Upvotes: 0
Reputation: 1460
CGFloat yOffset = scrollView.contentOffset.y;
CGFloat height = scrollView.frame.size.height;
CGFloat contentHeight = scrollView.contentSize.height;
CGFloat distance = (contentHeight - height) - yOffset;
if(distance < 0)
{
return ;
}
CGPoint offset = scrollView.contentOffset;
offset.y += distance;
[scrollView setContentOffset:offset animated:YES];
Upvotes: 0
Reputation: 999
I modified @jer's solution a little:
if([yourScrollView contentSize].height > yourScrollView.frame.size.height)
{
CGPoint bottomOffset = CGPointMake(0, [yourScrollView contentSize].height - yourScrollView.frame.size.height);
[yourScrollView setContentOffset:bottomOffset animated:YES];
}
This will scroll the content to the bottom of the UIScrollView, but only when it needs to be done (otherwise you get a weird up/down jumping effect)
Also I noticed if you don't minus the hight of the scrollview itself from the height of the content it scrolls the content up past where is visible.
Upvotes: 6
Reputation: 20236
Use something like this instead:
CGPoint bottomOffset = CGPointMake(0, [yourScrollView contentSize].height);
[yourScrollView setContentOffset:bottomOffset animated:YES];
If you don't want it animated, just change YES
to NO
.
Upvotes: 3