How display shortened path in a label?

I have a single-line label whose purpose is display file path, possibly very long.

Is there any way to shorten/compact the path string (with ellipse ...) so that the label still displays full path even it's too long?

Like below:

/some/very/long/path/to/some/filename.txt to /some/.../filename.txt

Answered by darkpaw in 774973022

I think you can set the label's line break mode to "Truncate Middle", so very long text automatically gets an ellipsis in the middle.

I don't think that can be done automatically.

What I would do:

  • test the path length, with url.absoluteString
  • if too long, extract components.

In URL struct, you have pathComponents which gives you access to all components. From it, parse what you need (first and last).

Or you can use properties as:

  • fileUrl.lastPathComponent

Explanations in Xcode doc are useless. So have a look here for instance: https://cocoacasts.com/working-with-nsurlcomponents-in-swift

That can be done quite easily. But what I want is a more 'strict' way.

I'd like to know if Cocoa/Appket provide some low-level mechnisms to measure if a long string fit in a constrained rectangle when it's displayed in a graphics context (here, an NSTextField). When it's not fit entirely, I can abbreviate some path components to make the path string shorter.

Accepted Answer

I think you can set the label's line break mode to "Truncate Middle", so very long text automatically gets an ellipsis in the middle.

I'd like to know if Cocoa/AppKit

If you’re on the Mac, be aware that AppKit has NSPathControl.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How display shortened path in a label?
 
 
Q