NSTextField delegate notifications — how to get text?

Deadly 提交于 2019-12-04 03:10:36

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.

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

}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!