Search code examples
iosiphoneobjective-cuiscrollview

How to use UIScrollView


I am trying to achieve something similar to the photo options bar in VSCO Cam. I tried setting it up with an image, just to get an idea on how to do it, but its not working.

I think one of the problems could be with the fact that the UIScrollView should be horizontal.

Here is my code:

  - (void)viewDidLoad
 {
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.


[self.scrollView setContentSize:CGSizeMake(646, 73)];

self.scrollView.scrollEnabled = YES;


UIImage *bleh = [UIImage imageNamed:@"Digits 2 1"];

UIImageView *raaaa = [[UIImageView alloc]initWithImage:bleh];

[self.scrollView addSubview:raaaa];

 } 

Solution

  • So the first thing you need to understand is the contentsize property.

    The subviews inside the scrollview are its "content". They can be arranged in any way you want inside the view.

    In order to make it scroll though, you need to let the scrollview know how much "space" its content is taking up.

    In your case, I'm going to guess that your image is 646 x 73 in dimensions. If you set the contentsize to that, the scrollview doesn't need to scroll because it can show all the content at once. However when you increase it, the scrollview now knows there is more content outside of the screen and it will allow you to scroll.

    The second thing you need to understand is the position of the subviews. If you set the frame of your imageview to (0,0,646,73), it will be in the "left-most" position inside the scrollview. Thus, it will only scroll to the right (the white space you see).

    Try this code and see if you can understand whats happening:

    [self.scrollView setContentSize:CGSizeMake(1292, 73)];
    
    UIImage *im = [UIImage imageNamed:@"Digits 2 1"];
    
    UIImageView *v1 = [[UIImageView alloc]initWithImage:im];
    UIImageView *v2 = [[UIImageView alloc]initWithImage:im];
    
    v1.frame = CGRectMake(0,0,646,73);
    v2.frame = CGRectMake(646,0,646,73);
    [self.scrollView addSubView:v1];
    [self.scrollView addSubView:v2];