Search code examples
iphoneobjective-cios4uiscrollviewcontentsize

Set starting point of content size for UIScrollView


How do I set the starting point of a UIScrollView? I would like to add a UIImageView left of the UIScrollView but changing the contentSize only adds scrolling room to the right of the scrollview. How do I add an ImageView left of the scrollView's (0,0) point and make it part of the scrollview's content size?


Solution

  • Hopefully I've got what you're trying to do here. I think this just takes a few turns with the contentOffset to get right.

    Starting off;

    • Add the scrollView at frame (0,0,320,480) - its a full screen scroller
    • set contentSize to (320*3, 480) - it now has a content with the width of 3 'pages'
    • Add your imageView as a subview to the scrollView at frame (320,0,320,480)
    • set contentOffset of the scrollView to (320, 0) - this will move the content of the scrollView left, in the negative x direction by 320
    • Now your imageView will be on screen, but it will have a 320px width both on the left and right on the scroller content.

    (Note that in the code below, i've simply added a UIView and not an imageView)

    UIScrollView *scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    scroller.delegate = self;
    scroller.pagingEnabled = YES;
    scroller.backgroundColor = [UIColor blueColor];
    scroller.contentSize = CGSizeMake(960, 480);
    
    UIView *imgView = [[UIView alloc] initWithFrame:CGRectMake(320, 0, 320, 480)];
    [imgView setBackgroundColor:[UIColor redColor]];
    [scroller addSubview:imgView];
    
    [scroller setContentOffset:CGPointMake(320, 0)];
    [self.view addSubview:scroller];
    

    Does that help?