Naveed Rafi
Naveed Rafi

Reputation: 2633

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. 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

Answers (5)

Marek R
Marek R

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

Sohel L.
Sohel L.

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

8suhas
8suhas

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

Tobi
Tobi

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

jer
jer

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

Related Questions