NSTextField sizeToFit or update frame update left

I have a strange problem with the sizeToFit method on an NSTextField.

I have an NSView where I create CALayer and NSTextField. I use the sizeToFit method to resize my CALayer to fit the field value. It works well, but when I insert a space, the text shifts to the left inside the field frame (see image below).

Both layers and text box borders are well placed (origin does not move).

Any hint about this would be much appreciated.

text shift

EDIT A frame update has the same behavior, even if sizeToFit is not used.

Sometimes it moves when you insert a space or sometimes it returns to the desired position when you insert a space.

The sublayer does not move from its source.

EDIT It seems that the NSTextField container has enough space to display. I found that there is enough space for this.

We cannot access the NSTextField container, so we add a large value to the line width (depending on the font size) before calling the frame update or [self sizeThatFits:stringSize]; and [self sizeToFit]; .

+6
source share
1 answer

I think there is no need for the -sizeToFit method. It is automatically called when the layout is executed. If you need to adjust the size of your NSTextField -instance, subclass it and override the -intrinsicContentSize method.

I used this approach with the "fade out" -text mask at the end of the text field. Using the autodetection value and internal content, my text fields have always been with this mask, even if there was enough space for the layout on the parent view.

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

Each time you need to "update" the size of the text field (when typing?), Call -invalidateIntrinsicContentSize .

+1
source

Source: https://habr.com/ru/post/985106/


All Articles