0
votes

I have a UIScrollView that should only scroll horizontally. The scroll view is pinned to the bottom of the screen. I have set auto layout constraints to a fixed height. I set the contentSize to a fixed size.

However, when I run the application the content is showing half of it off the bottom of the screen. And it will scroll vertically for what seems to be about 200 pixels.

I have a map and a label pinned above the scroll view and the layout looks exactly as I want, except the content of the scroll view seems off. This is the code I've written:

in my .h file:

@interface MapViewController : UIViewController <UIScrollViewDelegate>

in viewDidLoad:

self.scrollView.delegate = self;
[self.scrollView setContentSize:CGSizeMake(600, 100)];

// add some content
UIView *personView = [[UIView alloc] initWithFrame:CGRectMake(0, 8, 100, self.scrollView.frame.size.height-16)];
personView.backgroundColor = [UIColor cyanColor];

UIView *personView2 = [[UIView alloc] initWithFrame:CGRectMake(110, 8, 100, self.scrollView.frame.size.height-16)];
personView2.backgroundColor = [UIColor redColor];

UIView *personView3 = [[UIView alloc] initWithFrame:CGRectMake(220, 8, 100, self.scrollView.frame.size.height-16)];
personView3.backgroundColor = [UIColor blueColor];

UIView *personView4 = [[UIView alloc] initWithFrame:CGRectMake(330, 8, 100, self.scrollView.frame.size.height-16)];
personView4.backgroundColor = [UIColor orangeColor];

[self.scrollView addSubview:personView];
[self.scrollView addSubview:personView2];
[self.scrollView addSubview:personView3];
[self.scrollView addSubview:personView4];

I don't use UIScrollView that often, so am I missing something? Does anyone know where the sizing problem could be coming from?

Also I did an NSLog on the frame height and contentSize height and both equal 100.

Edit:

This view is in a navigation controller and I set the navigation bar from hidden = YES to hidden = NO on first load. I've noticed that the content height is different when I leave it hidden, so this must have something to do with it.

1
If you're using constraints, you should not set the contentSize. You should use constraints to control contentSize. Read Technical Note TN2154: UIScrollView And Autolayout.rob mayoff
@robmayoff is there a way to work around using constraints for contentSize, seems like theres an easier solution. Also you left out panama at the end of your palindrome on your bio :)MSU_Bulldog

1 Answers

3
votes

Try to set your scrollView's Content size int "viewDidLayoutSubviews" method with keeping the autolayouts set.

-(void)viewDidLayoutSubviews
{
  [self.scrollView setContentSize:CGSizeMake(required_width, required_height)];
}

Check the Navigation Bar set to the ViewController in the Storyboard as well. If there is any, try removing it.

And please lemme know if you still face some problem.