3

I am working with interface builder to create a xib. This xib has a uiview that contains a uitextview. Both are supposed to resize as the text in the uitextview changes. The constraints look a lot like this:

enter image description here

The pink UITextView pushes on the blue superview. The blue uiView has a minimum width of 189 px and a trailing constraint of at least 8px.

For the most part this works. Really long sections of text resize the two views to the fullest extent allowed as intended and if there are only one or two words, the views stay small. However, the problem is when you have a short sentence.

In this case, the views only expand to about 189px, and the text moves to the second line even though there is space to expand.

Here is what it looks like when you only put a few words in: enter image description here

and here is a fully expanded box:

enter image description here

I have tried to make the trailing constraint have a lower priority than the others, and I have tried modifying the content hugging and compression resistance properties in many ways without success.

How can I make the views expand so that they fit the text content with the fewest number of lines? There are no restrictions on height, only on width.

Any help would be appreciated!

vvMINOvv
  • 1,768
  • 4
  • 22
  • 45

3 Answers3

0

Get the new size of the textView using this method

CGSize sz = [_textView.text sizeWithFont:_textView.font]

in case that didn't work very well with the height,get the width you just got from the preivous method and use in the next method to get the appropriate height you need

- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
    UITextView *textView = [[UITextView alloc] init];

    [textView performSelectorOnMainThread:@selector(setAttributedText:)
                                    withObject:text
                                 waitUntilDone:YES];

    CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}
Mohammad Allam
  • 258
  • 2
  • 14
0

The key is to set the preferredMaxLayoutWidth to something big (320px sounds good. Your right constraint is going to limit it anyways).

You can do that in your code as

[self.label setPreferredMaxLayoutWidth:320];

Or from the Interface Builder as follows:

Setting properties from Interface Builder

This way you'll see the label expanding as expected:

Example

fz.
  • 3,233
  • 22
  • 20
-1

Have you tried the solution presented in this post?

Dynamic expand UITextView on ios 7

I believe you have to set your UITextView to sizeToFit

[YourUITextView sizeToFit];
Community
  • 1
  • 1
Sophy Swicz
  • 1,307
  • 11
  • 21
  • I'm afraid that didn't help at all. I placed in different areas, following the advice in the post you've linked as well. None seem to be working. Perhaps it's important to note that I'm using the interface builder to set these – vvMINOvv Apr 23 '14 at 18:59