Cocoa Bindings Quickie

 

Just to sweat it out, I’ve been working on adding a cool HUD-style Inspector to an app I’m working on. The thing is I’ve been doing it all by hand. As in creating the whole freaking window, text, everything on the window, from code. Not an easy process and it gives me so much appreciation for Interface Builder!

The thing is I needed to bind a NSTextField to some values from an array controller. Not that big of a deal setting them up in code, but then I decided that to simplify my life, I would need to bind them with the “displayPatternValueX” option, instead of just binding to :@”value”. So, without further ado, here is a snippet of code that produces a single textfield on the window bound to my controller with a sorta label before the actual bound value. It’s almost magic!

1
2
3
4
5
6
7
8
9
10
11
12
13
/* Rating */
NSTextField *ratingField = [[NSTextField alloc] initWithFrame:NSMakeRect(10+20, y_position – 2050, windowSize.width-(2*(10+20)), textHeight+5)];
 
[[window contentView] addSubview:ratingField];
[ratingField setEditable:NO];
[ratingField setSelectable:NO];
[ratingField setFont:[NSFont systemFontOfSize:textHeight]];
[ratingField setTextColor:[NSColor whiteColor]];
 
[ratingField setDrawsBackground:NO];
[ratingField setBordered:NO];
[ratingField setStringValue:@"%{value}@ Bookmarks"];
[ratingField bind:@"displayPatternValue1" toObject: [parent BookmarksController] withKeyPath:@”selection.rating” options:[NSDictionary dictionaryWithObject: [NSString stringWithString:@"Rating: %{value1}@ "] forKey:@”NSDisplayPattern”]];

Just need to keep in mind that the magic code does what you can easily do in IB. Just to clarify, this is in a separate NIB and I’m essentially using File’s Owner as my binding object, except I used [parent BookmarksController] to access this. In IB I would have bound to File’s Owner with a modelKeyPath of @”BookmarksController.selection.bookmarkName” to get the same result. Tricky part was getting the NSDictionary setup using the constant @”NSDisplayPattern” to get the pattern to work.

1
[ratingField bind:@"displayPatternValue1" toObject: [parent BookmarksController] withKeyPath:@"selection.rating" options:[NSDictionary dictionaryWithObject: [NSString stringWithString:@"Rating: %{value1}@ "] forKey:@"NSDisplayPattern"]];

Hope that all helps someone since I can’t find any documentation on the subject online. There’s plenty to explain it for IB, but there aren’t any examples of doing it by hand. Thought I would throw that out there.

Comments (0) Leave a Comment
  1. No comments yet.

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">
  1. No trackbacks yet.