3

I am trying to implement an NSTextView which resizes to fit its content. I am trying to make it so it has a maximum amount of lines. Meaning, that when this limit is reached, it will not grow any further and the user will be able to scroll it.

There seem to be a lot of people wanting this but I have not found a complete implementation of this.

The idea is to take the content size of the NSTextView and resize it so that it matches. I just can't figure out how to set the layout size of the NSTextView. It does not seem to be it's frame which needs to be set and which one might expect.

Can anyone please tell me how to set the frame of the NSTextView?

simonbs
  • 7,932
  • 13
  • 69
  • 115

1 Answers1

4

It turns out that it's the height of the scroll view which should be changed. Changing the height of an NSTextView can be done by overwriting the -didChangeText method like below.

- (void)didChangeText
{
    NSScrollView *scrollView = (NSScrollView *) self.superview.superview;
    NSRect frame = scrollView.frame;

    // Calculate height
    NSUInteger numberOfLines = [self numberOfLines];
    NSUInteger height = frame.size.height;
    if (numberOfLines <= 13)
    {
        height = 22 + (numberOfLines - 1) * 14;
        if (height < 22)
            height = 22;
    }

    // Update height
    frame.size.height = height;
    self.superview.superview.frame = frame;
}

Play around with the constants to get the result you wish for.

simonbs
  • 7,932
  • 13
  • 69
  • 115