It is best to use NSTextView instead of NSTextField . If you use NSTextView , you can get NSTextContainer NSTextView using the textContainer property. A container can tell you containerSize (a space into which the text is inserted).
NSString objects respond to the sizeWithAttributes: method. You can use the resulting NSSize structure to capture the width of the text if you draw using the specified attributes. See the “Constants” section of the NSAttributedString application set reference for a list of attributes that are relevant.
If the containerSize less than the width of sizeWithAttributes: text will be truncated.
EDIT: Sorry, this is only true in the absence of lineFragmentPadding , but by default lineFragmentPadding is nonzero. Either subtract textContainer.lineFragmentPadding from containerSize.width , or use the NSTextContainer setLineFragmentPadding: method to set it to 0 .
I suppose you could also make some assumptions regarding the text area with respect to the size of the NSTextField and use the sizeWithAttributes: NSString method in conjunction with this, but it is not so clean.
EDIT 2: I realized that I did not pay attention to the OP's interest in breaking text with ellipses. The following code example uses truncation in an NSTextView . I also thought that I could also add code that makes NSTextView little more similar in appearance to NSTextField , putting it inside an NSBox . Adding a size check to determine whether a tooltip should be displayed will be a simple addition to the code below using the information already mentioned above.
NSString* string = @"Hello World.";
Mathew
source share