Search code examples
iosobjective-cuiscrollviewuiscrollviewdelegate

How can I set the width of the ScrollView content?


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!


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)];