在 Cocoa 中呈现来自 XIB 的模态对话框:最佳/最短模式?

Posted

技术标签:

【中文标题】在 Cocoa 中呈现来自 XIB 的模态对话框:最佳/最短模式?【英文标题】:Presenting modal dialogs from XIB in Cocoa: best/shortest pattern? 【发布时间】: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 运行],所以从这个模块的用户的角度来看,它看起来很简单,但当你往里面看时就不那么简单了。

【问题讨论】:

这个问题可能更适合codereview.stackexchange.com @JRG-Developer 也在那里问,谢谢指出。 codereview.stackexchange.com/questions/37640/… 【参考方案1】:

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

- (IBAction) buttonAction:(NSButton*)sender

    [NSApp stopModalWithCode:[sender tag]];
    [self.window close];

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

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

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

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

【讨论】:

我根据你的答案发布了一个答案,这里有完整的源代码:codereview.stackexchange.com/questions/37640/…

以上是关于在 Cocoa 中呈现来自 XIB 的模态对话框:最佳/最短模式?的主要内容,如果未能解决你的问题,请参考以下文章

为啥在呈现这个模态视图时会有延迟?

Cocoa - 在情节提要中以编程方式呈现 NSViewController LIKE “显示选项”(不是模态)

如何从模态 XIB 设置 VC 的背景颜色

如何为模态对话框中呈现的对象运行观察函数?

来自 NSWindowController Cocoa 的自定义视图

如何在 Cocoa 应用程序中手动创建和附加 MainMenu.xib?