开发者

Cocoa Objective C - How to end editing of NSTextField when user presses Enter key or clicks out side text box

I have created two cocoa controls on my GUI. NSButton and NSTextField. When user clicks on the button, button handler will be executed. It will make butt开发者_如何学Con disable and NSTextField enable. On end editing, the string of text field will be shown as a button title.

button click
{
 - Make button visible = false;
 - Make text field visible = true;
 - Text field allow selection = true;
 - text field allow editing = true;
}

control text end editing
{
  - text field allow selection = false;
  - text field allow editing = false;
  - Set button title as text field string;
  - Set text field visible = false;
  - Set button visible = true;
}

I have written above two functions to achieve the functionality. I am getting required functionality when user presses Tab key, as the view switches to next view. But, I want that, once user enters required text in the text field, he can press Enter or click outside of text field to end editing.

On end editing, text field should be closed and text written should be displayed as a title of button.

Please let know, how this functionality can be achieved. Any help would be appreciated.

Thanks in advance...


I'd make an object the delegate of your NSTextField and then implement the delegate method:

- (void)controlTextDidEndEditing:(NSNotification *)aNotification
{
   - text field allow selection = false;
   - text field allow editing = false;
   - Set button title as text field string;
   - Set text field visible = false;
   - Set button visible = true;
}

I believe this captures both the case where you hit enter and where you tab out.


When user presses Enter key:

Implement NSTextFieldDelegate and attach to the text field. Implement the delegate method:

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
    if (commandSelector == @selector(insertNewline:)) {// @selector(cancelOperation:) for esc clicked
        [self.view.window makeFirstResponder:nil];
    }

    return NO;
}


When user click outside of the box:

Check my another answer for how to end editing when clicks outside of the box.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜