【问题标题】:Wait for user close window to get values from NSTextField - Cocoa等待用户关闭窗口从 NSTextField 获取值 - Cocoa
【发布时间】:2015-09-30 18:31:12
【问题描述】:

我正在 Cocoa 中开发一个带有一个按钮和一个 NSTextField 的 GUI。单击按钮时,会弹出另一个窗口,其中包含一个 NSTextField 和两个按钮:确定按钮和取消按钮。用户可以在第二个窗口的 NSTextField 中输入一些文本,当这个窗口关闭时,相同的文本会转到第一个窗口的 NSTextField。

我的问题是:如何让我的应用程序等待用户关闭第二个窗口来更新第一个寡妇的 NSTextField?如果用户在第二个窗口中单击取消按钮,我不想在第一个窗口中更改任何内容。

只有模态窗口才有可能吗?

提前致谢,

雷南

【问题讨论】:

    标签: objective-c macos cocoa


    【解决方案1】:

    使用工作表的简单解决方案

    • 在 Interface Builder 中,在与主窗口相同的 .xib 中创建一个新窗口,使其大小小于主窗口。

    • 取消选中CloseMinimizeResizeVisible At Launch。 确保选中Title Bar(否则会破坏第一响应者)。

    • 添加一个NSTextField和两个NSButton,设置OK按钮的tag为1。

    • 在.h文件中添加

      @property (weak) IBOutlet NSTextField *textField;
      @property (weak) IBOutlet NSWindow *sheet;
      
    • 在.m文件中添加

      - (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是主窗口中的NSTextField实例

    在 Interface Builder 中新创建的窗口中

    • 将 NSWindow 出口连接到IBOutlet sheet
    • 将 NSTextField 出口连接到IBOutlet textField
    • 将两个 NSButton 的操作连接到 IBAction dismissSheet
    • 将显示工作表的UI元素的动作连接到IBAction showSheet

    【讨论】:

    • 我也建议在这种情况下使用工作表窗口。但是如果你不想使用工作表窗口,你可以使用 NSWindowWillClose 委托属性。像这样的例子 secondWindow.delegate = controller; //在你的控制器中 - (void)windowWillClose:(NSNotification *)notification{//在第一个窗口中更新你的文本框}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多