Question

Im working on a scrollview and I want it to be with paging enabled, but when I try to set a custom width to the content I cant, I need someones help, Thanks!

Heres what Im trying:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {

    int PageNum = (int)(scrollView.contentOffset.x / 140);
    targetContentOffset->x = PageNum * (int)(targetContentOffset->x / PageNum);

}

When scrollViewDidScroll: I add a NSlog and Its printing correctly the current page, what does not work is the custom for the paging width:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    int PageNum = (int)(scrollView.contentOffset.x / 140);
    NSLog(@"%d", PageNum);

}

Hope someone can Help me, thanks!

Was it helpful?

Solution

You do not have to implement scrollViewWillEndDragging:withVelocity:targetContentOffset: method to enable paging in a UIScrollView. To do this, you need only:

  • Set pagingEnabled property of your scrollview to YES. Documentation says about this property: If the value of this property is YES, the scroll view stops on multiples of the scroll view’s bounds when the user scrolls.
  • Add your subviews (pages) to the scrollview. Their widths must be equal to the scrollview's width, to retrieve a horizontal-paged scrollview.
  • Set your scrollview's contentSize property.

So your code should be something like this:

[scrollView setPagingEnabled:YES];
NSInteger numberOfPages = 100;

CGFloat pageWidth = scrollView.bounds.size.width;
CGFloat pageHeight = scrollView.bounds.size.height; // can be something else

for(NSInteger i = 0; i < numberOfPages; i++)
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(i * pageWidth, 0, pageWidth, pageHeight)];
    // do somethings with the page view
    [scrollView addSubview:view];
}

[scrollView setContentSize:CGSizeMake(numberOfPages * pageWidth, scrollView.bounds.size.height)];

OTHER TIPS

Frankly I do not really understand your code and what you are up to. This answer may not even be related to your problem, but it may help anyway.

targetContentOffset->x = PageNum * (int)(targetContentOffset->x / PageNum);

is quite an equivalent to

targetContentOffset->x = (int)(targetContentOffset->x);

which does not seem to do much but some rounding. If you do this for the side-effects of the rounding then ignore my answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top