Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ellipsize NSTextField?

Is there a way to ellipsize the text content of an NSTextField, instead of truncate?

So instead of:

The quick brown fox jumped over

It would say:

The quick brown fox jumped ...

I can't find anything in the documentation for this. What am I missing?

UPDATE: Is there any way to ellipsize AND wordwrap--in other words, have multiple lines and ellipsize the last?

like image 272
Chad Schultz Avatar asked Aug 03 '12 22:08

Chad Schultz


1 Answers

So this is a great question! Even though its exposed in IB, its not a property on the view or any subview. Instead its buried as a property on the cell used by NSTextField. So if you ask that object for its cell, you can then read or set the value: lineBreakMode.

Look in the class description for NSCell for all the options - truncateCenter is one (to get center ellipsis).

EDIT: the following thoughts were prompted by the updated question. Personally, I think trying to get that google code is way overkill and perhaps you can do something less complex by creating a mini-custom textField.

  • create a customer NSView object and give it a string and font property and some methods related to the actions below, and perhaps even a width property

  • essentially the idea is to use the Cocoa NSString category that lets you determine the length of string (and probably its height) from a string/font combo (I use this in UIKit, did use equivalents in Cocoa, but its been a while...)

  • one of your view's methods will be 'calculate'. When you get this, covert the string to an array of words using a single space as the separator (or make it more complex). Then, start computing the length of the drawn string, taking the first work, append a space and the second, etc, until you find you have exceeded he width. This is your first line string.

  • continue doing this for the number of lines that you want to draw (2? 3?). Calculate the length of the unicode char that does ... - its option semicolon as I recall - and keep that around.

  • in the last line, keep adding words until you exceed the length, and then back up a word at a time, verifying that the last appended strings string (minus a trailing space) but with the '...' char will fit in the space.

  • you can make this fancier by adding padding around the border etc.

  • once the calculation is finished (and you of course cache all the bits of the answer), your view is prepared when it gets 'drawRect:...'. You position at (0, bounds.size.height - 21) and draw the first segment, then move down 21 points and draw the second line, etc.

If I were to code this I would plan on 2-4 hours - its not trivial, perhaps the logic is a bit complex, but its straightforward. Good luck!

like image 103
David H Avatar answered Sep 20 '22 12:09

David H