D4rWiNS
D4rWiNS

Reputation: 2615

Implementing vertical UIScrollView

After 2 days behind the implementation of a UIScrollView, I give up to do it by myself, despite It should be simple but I am not able to make it.

I need a vertical scrollview with Autolayout (I have 2 backgrounds images that need to scale), I have Xcode 7.2, iOs deployment target 9.0 and I am using the storyboard

The scrollview is a "new account" form with a lot of content, So it can have a fixed height

I tried lots of options but no one of them work, at the momment I have a scrollview with a "content view" with all of the components.

Problems: 1.- How can I put more content in the scrollview? If I try to put more compoments(more than the height of ViewControler), it automatically moves my components to be inside the ViewController rectangle

2.- How I can make it scrollable? If I pin the content view to the top, bottom, left, right and make it with fixed height (like 1000) it doesn't scroll

Any help would be appreciated

Upvotes: 0

Views: 70

Answers (1)

Bharath Vankireddy
Bharath Vankireddy

Reputation: 932

Scrollview will scroll until the end of last UI object. But this is not the default behaviour of the scrollview. You should explicitly set the contentSize on your scrollview. Check below example.

-(void)addImage {
  int count = 20;
  UIScrollView * scView = [[UIScrollView alloc] init];
  scView.frame = CGRectMake(30, 60, self.view.frame.size.width, 60);
  UIButton * btn;
  UIImageView * imgV;
  float imgWidth = 44;
 for(int i=0;i<count;i++) {
   imgV = [[UIImageView alloc] init];
   imgV.frame = CGRectMake(i*imgWidth, 0, imgWidth, 44);
   imgV.image = [UIImage imageNamed:@"gitar"];
   [scView addSubview:imgV];
 }
[scView setContentSize:CGSizeMake(imgWidth*count, 50)];
[scView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:scView];
}

What the above method does is, it will add 20 images in scrollview and at the end after adding all the images to scrollview in for loop I set contentSize to Scrollview. This step makes my scrollview to scroll until the content available. My example showing for Horizontal scroll, you have to change this behaviour to vertical scroll.

Upvotes: 1

Related Questions