Search code examples
swiftautolayoutnstextfieldappkit

Truncate text in label


I am trying to use "Truncate Middle" on a single line label. I checked "Uses Single Line Mode", set Layout to "Truncates" and Line Break to "Truncate Middle" and I've set the Preferred width of the text field to "First Runtime Layout Width" and Content Hugging Priority to 250.

Here's my layout with the <Title> label on which I am trying to enable the truncation: layout

In my ViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    titleLabel.stringValue = "This is a very very long title that should be truncated because it would enlarge the window unnecessary!"
}

It does not work, the window is enlarged to show the complete title and the user can't reduce its width.

Strangely, if I change the layout and line break from "Truncates"/"Truncate Middle" to "Wraps"/"Character Wrap", it works fine, but without the middle truncation.

screenshot with wrap

I am expecting truncate to work like this:

This is a very very long text...rge the window unnecessary!

Maybe I'm missing something?

EDIT: Here's the sample project to test the issue: https://nofile.io/f/9s9OJXHaaw1/TestTruncate.zip


Solution

  • If you use Auto Layout for your NSTextView and surrounding NSView you should set your Content Compression Resistance Priority of the NSTextView less than NSLayoutPriorityWindowSizeStayPut (e.g. 499). Otherwise your NSTextView will not truncate its content. (Reference)

    I was able to achieve this by setting Content Compression Resistance Priority of Horizontal from 500 to 499.

    You can do so by selecting your label -> Size Inspector -> Content Compression Resistance Priority

    enter image description here

    Giving me the following output:

    enter image description here