【问题标题】:Presenting modal dialogs from XIB in Cocoa: best/shortest pattern?在 Cocoa 中呈现来自 XIB 的模态对话框:最佳/最短模式?
【发布时间】:2013-12-09 18:16:49
【问题描述】:

下面是我的典型 WindowController 模块,用于呈现从 XIB 加载的模式对话框(可能是设置、询问用户名/密码等)。对于这样的事情来说,这似乎有点太复杂了。有什么想法可以用更少的代码更好地完成吗?

没关系,它要求输入密码,它可以是任何东西。最让我沮丧的是,我在每个基于 XIB 的模态窗口模块中都重复了相同的模式。这当然意味着我可以定义一个自定义窗口控制器类,但在此之前我需要确保这确实是最好的处理方式。

#import "MyPasswordWindowController.h"

static MyPasswordWindowController* windowController;

@interface MyPasswordWindowController ()
@property (weak) IBOutlet NSSecureTextField *passwordField;
@end

@implementation MyPasswordWindowController
{
    NSInteger _dialogCode;
}

- (id)init
{
    return [super initWithWindowNibName:@"MyPassword"];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self.window center];
}

- (void)windowWillClose:(NSNotification*)notification
{
    [NSApp stopModalWithCode:_dialogCode];
    _dialogCode = 0;
}

- (IBAction)okButtonAction:(NSButton *)sender
{
    _dialogCode = 1;
    [self.window close];
}

- (IBAction)cancelButtonAction:(NSButton *)sender
{
    [self.window close];
}

+ (NSString*)run
{
    if (!windowController)
        windowController = [MyPasswordWindowController new];
    [windowController loadWindow];
    windowController.passwordField.stringValue = @"";
    if ([NSApp runModalForWindow:windowController.window])
        return windowController.passwordField.stringValue;
    return nil;
}

应用程序调用 [MyPasswordWindowController 运行],所以从这个模块的用户的角度来看,它看起来很简单,但当你往里面看时就不那么简单了。

【问题讨论】:

标签: objective-c cocoa modal-dialog xib nswindowcontroller


【解决方案1】:

在按钮上设置标签以区分它们。让它们都针对相同的操作方法:

- (IBAction) buttonAction:(NSButton*)sender
{
    [NSApp stopModalWithCode:[sender tag]];
    [self.window close];
}

摆脱您的 _dialogCode 实例变量和 -windowWillClose: 方法。

-[NSApplication runModalForWindow:] 已经将窗口居中,因此您可以摆脱 -awakeFromNib 方法。

摆脱对-[NSWindowController loadWindow] 的调用。那是一个覆盖点。你不应该打电话给它。 The documentation 在这一点上很清楚。当你请求窗口控制器的-window时会自动调用。

摆脱MyPasswordWindowController 的静态实例。每次只分配一个新的。保留旧的没有意义,重复使用 Windows 可能会很麻烦。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多