user2255616
user2255616

Reputation: 35

Can't set UITextView height from its content

I am trying to set the height of the UITextView based on the amount of text it will be displaying. I found this solution to this on here:

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

But I can not get it to work, I think it is something to do with me not adding the UITextView to the view using addSubview correctly, but I can not figure it out! I am sure it is quite an easy fix.

Here is my viewcontroller.m file code

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize textView = _textView;


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.



    [self.view addSubview: _textView];

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



}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Upvotes: 2

Views: 3023

Answers (2)

Roshit
Roshit

Reputation: 1579

Instead of waiting for the Content Size, which you will get in ViewWillAppear, why dont you try this:

  • Find the height a particular text will need using - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
  • Set that to the frame of the textview directly.

And this is something that you can achieve in the - (void)viewDidLoad method itself.

- (void)viewDidLoad {
    NSString *aMessage = @""; // Text
    UIFont *aFont = [UIFont systemFontOfSize:20]; // Font required for the TextView
    CGFloat aTextViewWidth = 180.00; // Widht of the TextView
    CGSize aSize = [aMessage sizeWithFont:aFont constrainedToSize:CGSizeMake(aTextViewWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat aTextViewHeight = aSize.height;

    UITextView *aTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, aTextViewWidth, aTextViewHeight)];
    // Rest of your Code...
}

Upvotes: 1

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

You cannot do it in viewDidLoad since the textView frame hasn't been set yet.

Move your code in a more suitable method, such as viewWillAppear: or viewDidLayoutSubviews

- (void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];

   CGRect frame = _textView.frame;
   frame.size.height = _textView.contentSize.height;
   _textView.frame = frame;
}

If you want to understand better the lifecycle of a UIViewController's view, you may want to check out this very nice answer.

Upvotes: 3

Related Questions