UIScrollView contentsize is reset to zero when using auto layout

autolayout, ios, objective-c, uiscrollview

Solution

If you use auto layout with a `UIScrollView`, you don't set the `contentSize` property. See here for more information (scroll down to the section on `UIScrollView`).

Problem

I'm using `autolayout` to change the height of my `scrollview`. I add some `subviews` to the `scrollview` where I manually increment the content size. But when I get an event where I am about to change the height the content size is zero. Here is the code: ``` -(void) addTag:(NSString *)tagName { ... [button addTarget:self action:@selector(tagPressed:) forControlEvents:UIControlEventTouchUpInside]; [self setContentSize:CGSizeMake(self.frame.size.width, self.contentSize.height+60)]; [self.items addObject: button]; NSLog(@"content height: %0.2f", self.contentSize.height); } ``` Console Output: ``` 2013-04-18 18:23:06.106 TouchSelectApp[19944:c07] content height: 120.00 ``` Here I output the contentSize : ``` - (void)tagPressed:(UIButton *)sender { NSLog(@"1 content height: %0.2f", self.contentSize.height); ... } ``` The console shows: ``` 2013-04-18 18:17:24.747 TouchSelectApp[19944:c07] 1 content height: 0.00 ``` I don't why the content height is set to zero. Help Me! Update: Here is the problem I am trying to solve. I am have a scroll view with buttons. Initially it only shows one button. When the button is pressed tagPressed: is called. Tag Pressed changes the height to show all the buttons. Then when the user selects a button the scrollview's height is changed to the original and the offset is set to the button's origin. The below code works but the animation is all wrong. If I change the offset and before the animation block then it just sets the offset to zero. ``` - (void)tagPressed:(UIButton *)sender { CGPoint p; float maxHeight = self.items.count * 60; if (self.height.constant == maxHeight) { self.height.constant = 60; p = CGPointMake(0, sender.frame.origin.y-5); }else { self.height.constant = maxHeight; p = CGPointMake(0, 0); } [self.superview setNeedsUpdateConstraints]; [UIView animateWithDuration:0.5f animations: ^{ [self.superview layoutIfNeeded]; } completion:^(BOOL finished) { [self setContentOffset:p]; }]; ``` }

Original source

Related problems