6
votes

I have a strange issue with sizeToFit method on a NSTextField.

I have a NSView where I'm creating a CALayer and a NSTextField. I use the sizeToFit method to resize my CALayer according to the field value. It works well, but when I'm inserting a space, the text shifts on the left inside the field's frame (see image below).

Both layer's and text field's frames are positioned well (origin isn't moving).

Any clue on this would be highly appreciated.

text shift

EDIT Frame update has the same behavior, even when not using sizeToFit.

Sometimes it's shifting when inserting a space, or sometimes it's coming back to its wanted position when inserting a space.

The underlying layer doesn't move from its origin.

EDIT It looks like the container of the NSTextField needs enough space to display. What I discovered is that it needs actually a lot of space.

We can't access the container of a NSTextField, so I add a large value to the width of the string (depending on the size of the font) before calling a frame update or [self sizeThatFits:stringSize]; and [self sizeToFit];.

1
do you use autolayout?Daniyar
Yes, would it be different without autolayout ? I mean : this behavior is related to it ?Benoît Lahoz

1 Answers

2
votes

I think there's no need in -sizeToFit-method. It's automatically called when layout performs. If you need to adjust size of your NSTextField-instance, subclass it and override -intrinsicContentSize-method.

I used this approach with "fade out"-text mask at the end of the text field. Using autolayout and intrinsic content size my textfields were always with that mask even if on the parent view was enough space for layout.

- (CGSize)intrinsicContentSize
  {
   CGSize size=[super intrinsicContentSize];
   // adjust size somehow (or may be not)
   return(size);
  }

Each time you need to "update" text field size (while typing?), call the -invalidateIntrinsicContentSize.