scrolling the scrollview at the bottom programmatically - iphone
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. I开发者_StackOverflow社区t 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 ButtI 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.
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
.
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];
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!
This is more reliable
CGSize contentSize = scrollview.contentSize;
[scrollview scrollRectToVisible: CGRectMake(0.0,
contentSize.height - 1.0,
contentSize.width,
1.0)
animated: YES];
精彩评论