Resizing NSTextField to Fit Content

The NSPopOver, a new addition to the Cocoa toolkit since OS X 10.7, is an excellent way to give the user feedback on actions requiring their input. In my use case, I needed to be able to show an NSPopOver containing a multiline label populated with a string of varying length.


Getting the NSPopOver, NSView & NTextField all working perfectly was very basic.


Ensuring that the NSPopOver’s NSView & NSTextField resized appropriately was more challenging.


I needed to get the rectangle that my string would fill when drawn. A short Google search led me here: SO: NSString sizeWithAttributes: Content Rect. As I know I’ll be doing this again, I made a category of NSString that provides this.


The rest was simple:

1
2
3
4
5
6
7
8
9
10
11
NSSize size = [string sizeWithWidth:200.0 andFont:[textLabel font]];
 
[view setFrameSize:NSMakeSize(size.width + 30, size.height + 30)];
 
[textLabel setFrame:NSMakeRect(15, 15, size.width, size.height)];
[textLabel setStringValue:string];
 
popover.contentSize = view.frame.size;
[popover showRelativeToRect:[textField bounds] 
                     ofView:textField
              preferredEdge:NSMaxXEdge];

The NSString+Size category is available here: Cocoa Categories.

After doing this, I rethought my approach and streamlined it by creating a category on NSPopover, which is available in the above repository. I wrote about the process here: User Feedback & the NSPopover.

No comments | Trackback