Wait for user close window to get values from NSTextField

I am developing a GUI in Cocoa with a button and one NSTextField. When the button is clicked another window pop up with one NSTextField and two buttons: Ok button and Cancel Button. The user can entry some text in the NSTextField of the second window and when this window is closed the same text goes to the NSTextField of ther first window.

My question is: how can I make my application wait for the user to close the second window to update the NSTextField of the first widow? And if the user clicks the Cancel Button in the second window I don't wanna change anything in the first window.

Is it only possible with modal window?

Thanks in advance,

Rhenan


Simple solution with a sheet

  • In Interface Builder create a new window in the same .xib as the main window, size it smaller than the main window.

  • Uncheck Close , Minimize , Resize and Visible At Launch . Make sure that Title Bar is checked (otherwise will break first responder).

  • Add an NSTextField and two NSButtons, set the tag of the OK button to 1.

  • In the .h file add

    @property (weak) IBOutlet NSTextField *textField;
    @property (weak) IBOutlet NSWindow *sheet;
    
  • In the .m file add

    - (IBAction)showSheet:(id )sender
    {
      [self.window beginSheet:self.sheet completionHandler:^(NSModalResponse returnCode) {
        if (returnCode == NSModalResponseOK) {
           self.mainTextField.stringValue = self.textField.stringValue;
        }
      }];
    }
    
    - (IBAction)dismissSheet:(NSButton *)button
    {
       [self.textField.window makeFirstResponder:nil]; // force end editing
       [self.window endSheet:self.sheet returnCode:button.tag];
    }
    
  • mainTextField is the NSTextField instance in the main window

    In the new created window in Interface Builder

  • connect the NSWindow outlet to IBOutlet sheet
  • connect the NSTextField outlet to IBOutlet textField
  • connect the actions of both NSButtons to IBAction dismissSheet
  • connect the action of the UI element to show the sheet to IBAction showSheet
  • 链接地址: http://www.djcxy.com/p/85252.html

    上一篇: 根据验证(绑定)更改NSTextField文本颜色

    下一篇: 等待用户关闭窗口从NSTextField获取值