Last Updated: February 25, 2016
·
513
· elkraneo

autoheight text

Using dynamic source text inside scroll views can be problematic, especially if the design requires the text auto height, and not embedded in UISCrollView.

Offen we struggle searching for UIScrollView solutions, but the majority of found solutions doesn't take in count autolayout or dynamic font size in ios7.

The simple solution we find, consists in using UIlabel instead UItextView, making it multiline and refreshing the root UIScrollView with the final height of the UIlabel.

for example:

UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    UILabel *myText = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 100)];
    [myText setText:@"variable amount of text"];
    [myText setNumberOfLines:0];
    [myText sizeToFit];        

    [self.view addSubview:myScrollView];
    [myScrollView addSubview:myText];

    CGSize contentSize = CGSizeMake(320, myText.frame.size.height + myText.frame.origin.y);
    [myScrollView setContentSize:contentSize];