Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextField sizeToFit or frame update shift text to left

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];.

like image 870
Benoît Lahoz Avatar asked Apr 14 '15 09:04

Benoît Lahoz


1 Answers

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.

like image 87
Daniyar Avatar answered Nov 07 '22 10:11

Daniyar