I’ve searched around on how to perform this but I can’t find any answer.
I’d like to know if my NSTextfield is already truncating the text (… at the end) without having to check the length of its stringValue. I need to do this to know if I should set a tooltip on my NSTextfield (acting like a simple label).
The reason I don’t want to check the length of my textfield’s stringValue it’s because there are some characters that occupy more space than others, so that’s not very accurate
Thanks!
I’ve searched around on how to perform this but I can’t find any answer.
Share
Your best bet might be to use an
NSTextViewinstead of aNSTextField. If you use anNSTextViewyou can get theNSTextContainerof theNSTextViewusing thetextContainerproperty. The container can tell you thecontainerSize(the space the text is drawn in).NSStringobjects respond to the methodsizeWithAttributes:. You can use the resultingNSSizestruct to grab the width of the text if drawn with the given attributes. See the “Constants” section of the NSAttributedString Application Kit Additions Reference to figure out what attributes are relevant.If the
containerSizewidth is less than thesizeWithAttributes:width then the text will be truncated.EDIT: Apologies, this is only true with no
lineFragmentPadding, but the defaultlineFragmentPaddingis non-zero. Either subtract thetextContainer.lineFragmentPaddingfromcontainerSize.widthor use theNSTextContainersetLineFragmentPadding:method to set it to0.I suppose you could also make some assumptions about the text area relative to the size of the
NSTextFieldand use thesizeWithAttributes:NSStringmethod in conjunction with that, but that is not as clean.EDIT 2: I realized I did not address the OP’s interest in truncating the text using ellipses. The example code below uses truncation in the
NSTextView. I also thought I might as well throw in some code that makes theNSTextViewa little more similar in appearance to theNSTextFieldby putting it inside of aNSBox. Adding a check for size to determine if a tooltip should be displayed would be a simple addition to the code below using the information already mentioned above.