Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextField delegate notifications -- how to get text?

I've been trying to learn to use Xcode, but I'm getting confused with how to register that NSTextField has changed. Essentially, I have an NSTextField and a button. Clicking the button does stuff with the text in the field. However, I want to be able to get the text of the field without needing to use the text field "Action:send on end editing." That is, I want to be able to enter text and immediately press the button, without hitting enter or tabbing out of the text box. It seems like the way to do this would be by setting a delegate for my NSTextField that responds to

- (void)controlTextDidChange:(NSNotification *)aNotification

But I don't understand how to get the text that has been entered. I assume it has something to do with

[[aNotification userInfo] valueForKey:@"NSFieldEditor"];

but I really have no idea where to go from there.

like image 818
Daniel Avatar asked May 11 '11 19:05

Daniel


3 Answers

You're on the right track! The object that you get out of the notification's user info dictionary is the Field Editor, which is simply an NSTextView that's handling the text input on the text field's behalf.

Once you have that object, all you have to do is ask it for its textStorage, which is an NSTextStorage* object holding the text. That object, in turn, has its string which is a plain old NSString holding just the characters.

NSTextView * fieldEditor = [[aNotification userInfo] objectForKey:@"NSFieldEditor"];
NSString * theString = [[fieldEditor textStorage] string];

*A subclass of NSAttributedString, which is an object holding a string and associated "attributes" like color, font, and underlining.

like image 182
jscs Avatar answered Nov 11 '22 16:11

jscs


In your button action method, simply read the current string value in the text field:

- (IBAction)didClickTheButton:(id)sender {

    NSString* theString = [myTextField stringValue];

    // do something with theString

}
like image 37
Darren Avatar answered Nov 11 '22 16:11

Darren


If you're only ever handling a single text field, this may be simpler:

- (void)controlTextDidChange:(NSNotification *)obj {
    [self.inputField stringValue];
}

I'm totally ignoring all the complicated details of NSText and whatnot and just using the simplicity of the notification being sent and the simplicity of getting the string value from a text field.

like image 37
ArtOfWarfare Avatar answered Nov 11 '22 14:11

ArtOfWarfare