iosobjective-cuiscrollviewcontentsize

UIScrollView ContentSize.height is 0.0000 by default?


I am trying to create a dynamic form using a UIScrollView, but I noticed when I used a NSLog that my scrollView's contentSize.height = 0.00000 I built the scrollView to the width and height of the screen on storyboard with elements inside it. So why does it return 0? All the elements inside the scrollView are showing/functioning correctly. Does scrollView's contentSize always default at 0 and I just need to set it?


Solution

  • Yes is 0 by default. You should set the content size of your scrollview by summing all the views height and the spaces between them, example:

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
    scrollView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:scrollView];
    
    NSUInteger spaceBetweenLabels = 10;
    
    UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
    firstLabel.text = @"first label text";
    
    UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, spaceBetweenLabels + firstLabel.frame.size.height, 300, 40)];
    secondLabel.text = @"second label text";
    
    [scrollView addSubview:firstLabel];
    [scrollView addSubview:secondLabel];
    
    CGSize fullContentSize = CGSizeMake(300, firstLabel.frame.size.height + secondLabel.frame.size.height + spaceBetweenLabels);
    
    [scrollView setContentSize:fullContentSize];
    

    Of course if your scroll view height is higher than the content size height it won't scroll because everything is on the screen.