Jakub Bednar
Jakub Bednar

Reputation: 21

How to make NSStackView truncate right-most NSTextField

I have one line in my UI, that consists of fixed-sized string (FS), fixed-sized image and variable-sized string (VS). I need this line to be centered in its superview, possibly truncating the VS if it no longer fits in. Just like simple centered NSTextField with truncate enabled would do. But NSTextField can't hold an NSImage AFAIK.

I suppose NSStackView should be able to do this. I have set it up to be centered in its superview and have an NSTextField, NSImage and NSTextField inside. But when I set VS to something very long, both FS and VS are pushed out of superview bounds and clipped.

Is there a way to tell NSStackView to never move FS out of superview bounds and rather truncate VS? Or is there any other technique to achieve my goal?

What I have tried so far:

  1. Use NSStackView and set compressionResistance to 499 on the VS - no effect
  2. Use NSTextView - could not make it truncate text and fit on single line. Also seems like an overkill

  3. Use NSView - it requires me to set x-position so it is not properly centered.

I could use NSView and calculate sizes of the strings and modify constraints to make this work. But I think there must be a better way.

Thanks for any ideas,

J.

Upvotes: 2

Views: 621

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90521

It sounds like you haven't constrained the stack view to fit within its container. In addition to the centering constraint, you need to set its leading to be greater than or equal to the leading of the superview and its trailing to be less than or equal to the trailing of its superview.

The compression resistance of FS and the image view should be higher than the compression resistance of VS, and could even be required to prevent those two from ever being compressed.

The horizontal clipping resistance of the stack view should be higher than the compression resistance of VS. It's fine to leave it at required. You want VS to be compressed rather than clipped.

What the compression resistance of VS should actually be depends on the rest of your view hierarchy and constraints. It should presumably be less than 490 (NSLayoutPriorityDragThatCannotResizeWindow) so it doesn't force the window to resize.

Upvotes: 2

Related Questions