change UITextView height programmatically with the text

24,923

Solution 1

i think you need to do :

CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;

after the addsubview:

[self.view addSubview: self.textView];

Solution 2

Just send the sizeToFit message to the UITextView. It will adjust its own height to just fit its text. It will not change its own width or origin.

[textViewA1 sizeToFit];
Share:
24,923
Piero
Author by

Piero

Updated on November 30, 2020

Comments

  • Piero
    Piero over 3 years

    i want change the UITextView programmatically with the amount of text i set, and i have a problem, if i add a the UITextView with interface builder and i do this:

    CGRect frame = textViewA1.frame;
    frame.size.height = textViewA1.contentSize.height;
    textViewA1.frame = frame;
    

    all work fine, but if i create the UITextView programmatically, the height don't change, i do this:

     UITextView *textViewA1 = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 320, 50)];
    [textViewA1 setFont:[UIFont fontWithName:@"Enriqueta" size:15]];
    [textViewA1 setScrollEnabled:NO];
    [textViewA1 setUserInteractionEnabled:NO];
    [textViewA1 setBackgroundColor:[UIColor clearColor]];
    [textViewA1 setText:@"A lot of text"];
    CGRect frame = textViewA1.frame;
    frame.size.height = textViewA1.contentSize.height;
    textViewA1.frame = frame;
    

    in this way the height size of the uitextview don't change, how i can do?