hanumanDev
hanumanDev

Reputation: 6614

How to get a UITextView to dynamically size it's self to it's content

I'm trying to get a UITextView to dynamically size it's self to it's content. Sometimes the height of the text view will be 100 sometimes 700.

Everything I've tried so far hasn't worked.

I've tried the following in viewDidLoad and also in viewDidLayoutSubviews. here's the code:

CGRect frameDesc = self.descriptionDeal.frame;
frameDesc.size.height = self.descriptionDeal.contentSize.height;
self.descriptionDeal.frame = frameDesc;

self.descriptionDeal.backgroundColor = [UIColor redColor];

I added the background color so I could see the size of the view and it's not sizing to content.

I also tried:

    [self.descriptionDeal sizeToFit];

Also, not sure if it's affecting anything, but in the story where the UITextView is laid out the size is set there. I thought the code above would override it, but somethings not working correctly.

thanks for any help

Upvotes: 0

Views: 568

Answers (2)

7usam
7usam

Reputation: 1009

You should be making the size changes in your text view's delegate's textViewDidChange: method

Use https://stackoverflow.com/a/14956351/1311910 to get the appropriate height.

Upvotes: 1

Shashank
Shashank

Reputation: 1753

Try the following string methods which can be used to get the dimensions that would be required to display the string on to a view. You can change the textview's frame based on the CGSize that you get from one of these methods. Use this if you intend not to use auto layout in your project to support earlier versions of iOS.

- (CGSize)sizeWithFont:(UIFont *)font; // Uses NSLineBreakByWordWrapping
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode;
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size; // Uses NSLineBreakModeWordWrap
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode; // NSTextAlignment is not needed to determine size

Upvotes: 0

Related Questions