如何在Cocoa Mac Application中点击按钮打开一个新窗口?

Shi*_*han 33 macos cocoa xib

我想知道如何在Cocoa Mac Programming中点击按钮打开一个新窗口.帮我.我正在做一个mac应用程序,需要在特定按钮单击时打开一个新的mac窗口.

iPh*_*eDv 44

如果要为New Window创建单独的类,请执行以下步骤:

  1. 创建一个类,它是NSWindowController的子类,例如NewWindowController
  2. 为NewWindowController类创建一个窗口xib.
  3. 在按钮上单击代码为:

    NewWindowController *windowController = [[NewWindowController alloc] initWithWindowNibName:@"You Window XIB Name"];
    [windowController showWindow:self];
    
    Run Code Online (Sandbox Code Playgroud)

  • @Interfector:你的窗口立即关闭的原因可能是由于ARC.如果尚未将窗口控制器分配给强保持变量,则在函数结束后将立即释放它. (29认同)
  • 我尝试过同样的事情,但我遇到的问题是新窗口在显示后立即关闭.我没有任何代码,所以我不知道我做错了什么.有任何想法吗? (5认同)

Sau*_*abh 13

NSWindowController * wc=[[NSWindowController alloc] initWithWindowNibName:@"your_nib_name"];
[wc showWindow:self];
Run Code Online (Sandbox Code Playgroud)


Han*_*ans 10

Swift 3:在你的故事板中转到WindowController - > Identity inspector - > storyBoardID:填写:mainWindow.然后从您当前的viewcontroller链接故事板上的按钮到以下方法:

@IBAction func newWindow(_ sender: Any) {
    let myWindowController = self.storyboard!.instantiateController(withIdentifier: "mainWindow") as! NSWindowController
    myWindowController.showWindow(self)
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*cre 7

  1. 创建一个类,它是NSWindowController的子类,例如NewWindowController
  2. 为NewWindowController类创建一个窗口xib.
  3. 在按钮上单击代码为:

    NewWindowController *controllerWindow = [[NewWindowController alloc] initWithWindowNibName:@"You Window XIB Name"]; [controllerWindow showWindow:self];

是的,但如果此代码在某个函数内部,窗口将关闭.这是解决方案.

blah.h

@interface blah : NSObject {
     ...
     NewWindowController *controllerWindow;
     ...
}
Run Code Online (Sandbox Code Playgroud)

blah.m

@implementation
...
   -(IBAction)openNewWindow:(id)sender {
       controllerWindow = [[NewWindowController alloc] initWithWindowNibName:@"You Window XIB Name"];
       [controllerWindow showWindow:self];
    }
...
Run Code Online (Sandbox Code Playgroud)

  • 最好在现有答案中添加评论(如果可以的话),而不是引用它、回复,然后发布您自己的评论。 (2认同)