0

I'm trying to implement a custom 'NSTextField' that automatically resizes itself while the user insert text.

It's a simple enough task and here is the code I'm using:

- (void)textDidChange:(NSNotification *)aNotification
{
    [super textDidChange:aNotification];    
    [self invalidateIntrinsicContentSize];
}

- (NSSize)intrinsicContentSize
{
    if ( ![self.cell wraps] ) {
        return [super intrinsicContentSize];
    }
    NSRect frame = [self frame];
    CGFloat width = frame.size.width;
    frame.size.height = CGFLOAT_MAX;
    NSString *cellTitle = ((NSCell *)self.cell).title;
    CGFloat height = [self.cell cellSizeForBounds: frame].height;
    return NSMakeSize(width, height);
}

Which does the job. The curiosity is that if I comment the line that calls the NSTextField's cell title

NSString *cellTitle = ((NSCell *)self.cell).title;

it stops working. It seems that the cell doesn't update its title until requested. Of course if the cell's title doesn't change the textfield can't resize itself when the user type text.

Is this behaviour a feature or a bug?

As I said the code above does the job so this is more of a curiosity. The only annoyance is that the line produces a warning and I would like to know if there is a better way to do this.

Edit: Never mind I figured out the if I change the line to [(NSCell *)self.cell title]; the compiler stops complaining. The curiosity about feature or bug still stands though.

Jacopo
  • 1,031
  • 2
  • 12
  • 25

1 Answers1

0

"Returns the natural size for the receiving view, considering only properties of the view itself.

  • (NSSize)intrinsicContentSize

Return Value A size indicating the natural size for the receiving view based on its intrinsic properties.

Discussion Custom views typically have content that they display of which the layout system is unaware. Overriding this method allows a custom view to communicate to the layout system what size it would like to be based on its content. This intrinsic size must be independent of the content frame, because there’s no way to dynamically communicate a changed width to the layout system based on a changed height"

So when you typing, you should set the frame by yourself, if you get the length of string you typed, and the font, you can get the height of the string also the height of TextField. but some character you should be careful such as '\n'.
Community
  • 1
  • 1
paul
  • 137
  • 4