Search code examples
iosios6uitextviewios7viewwillappear

IOS7 get UITextView contentSize before viewDidAppear method is called?


I am upgrading my app from iOS6 to iOS7 and I am having some issues with my UIViewControllers layout. In iOS6 I was able to resize my UITextViews dynamically by getting the contentSize property of the textView and then setting its frame property. I would do all the resizing in the viewWillAppear method so that way the view would be resized before it was visible. Now in iOS7 it doesn't work. The only way the contentSize property works is if I set in the viewDidAppear method. I hate doing that because it causes the view to jump after it's already visible. Has anyone figured out how to solve this problem?

Here is my code that no longer works in iOS7:

-(void)viewWillAppear:(BOOL)animated
{
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(5, 0, 310, 0)];
    self.textView.text = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
    [self.view addSubview:self.textView];

    CGRect textViewframe;
    textViewframe = self.textView.frame;
    textViewframe.size.height = [self.textView contentSize].height;
    self.textView.frame = textViewframe;
}

Solution

  • You can call [self.textView layoutIfNeeded] after creating it with the appropriate frame (so it can figure out its max width) then contentSize should be representing the content.

    Also: If textView is defined as weak, the text view will be gone on the next line (as ARC adds a release and the optimizer moves it up). They announced this optimization change for Debug (-O0) builds during WWDC.