4

I'm subclassing NSTextView and using following code to calculate the intrinsic content size so that the height of the text view grows with it's content in my auto layout constraints.

- (CGSize)intrinsicContentSize
{
    return [[self layoutManager] usedRectForTextContainer:[self textContainer]].size;
}

This works except on the initial call where it returns (0,0) for the size.

If I call [self setNeedsLayout:YES] in my view after creating the text view and invalidate the text view's content size in -layout it will return the correct size for the new empty text view.

Is there a way to have -intrinsicContentSize return the correct size for my new text view without updating my view's layout?

Berry Blue
  • 15,330
  • 18
  • 62
  • 113
  • Call `invalidateIntrinsicContentSize`? – matt Feb 19 '14 at 05:21
  • By the way, the usual way to make a text view grow with its content is to look at its `contentSize`, which is maintained for you automatically.... – matt Feb 19 '14 at 05:25
  • @matt That's what I'm doing in -layout which works but I don't understand why I have to do this in -layout the first time. I invalidate the content size when the text changes which works fine. – Berry Blue Feb 19 '14 at 06:23
  • @matt NSTextView doesn't have a contentSize property unless I'm missing something. – Berry Blue Feb 19 '14 at 06:24
  • Yes, because I'm so used to iOS that I naturally was thinking in terms of UITextView. Please ignore everything I said (except in order to have a good laugh later on). – matt Feb 19 '14 at 06:25
  • If this _were_ iOS, my next suggestion would have been: is it possible that your "first time" is just too early? The text stack just isn't set up yet...? – matt Feb 19 '14 at 06:27
  • That's where I got the idea to invalidate the intrinsic content size in -layout since this gets called after everything is setup. – Berry Blue Feb 19 '14 at 20:12
  • Then it seems to me you have answered your own question (and that there's no problem). – matt Feb 20 '14 at 16:07

1 Answers1

1

Have a look at this thread, where Alexander Staubo shares a slightly adjusted version of your code. This works for me.

Community
  • 1
  • 1