使用 Swift 在 OS X 应用程序中打开新窗口
Posted
技术标签:
【中文标题】使用 Swift 在 OS X 应用程序中打开新窗口【英文标题】:Opening a new window in an OS X application with Swift 【发布时间】:2015-08-24 22:58:03 【问题描述】:我是 OS X 应用程序开发的新手,从状态栏菜单打开新窗口时遇到了一些问题。
我阅读了几个教程并尝试遵循它们。由于它们不完全适合我的项目,所以我做了一些修改,但似乎不起作用。
我创建了一个新的 NSWindowController 子类来设计一些 UI。但是当我点击菜单时,没有出现任何窗口。
//AppDelegate.Swift
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification)
// Insert code here to initialize your application
if let button = statusItem.button
button.image = NSImage(named: "StatusBarButtonImage")
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "About MyProgram", action: Selector("getAbout:"),keyEquivalent: ""))
statusItem.menu = menu
// open "About MyProgram" window
func getAbout(sender: AnyObject)
let controller = AboutWindowController()
controller.showWindow(self)
func applicationWillTerminate(aNotification: NSNotification)
// Insert code here to tear down your application
我不知道在新类中要写什么,所以我保留它是默认创建的。
//AboutWindowController.swift
import Cocoa
class AboutWindowController: NSWindowController
override func windowDidLoad()
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
任何帮助表示赞赏!谢谢!
【问题讨论】:
【参考方案1】:像这样工作,像这样编写代码
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
NSWindowController* wc;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
// Insert code here to initialize your application
NSStoryboard* storyboard = [NSStoryboard storyboardWithName:@"Main"
bundle:nil];
wc = [storyboard instantiateControllerWithIdentifier:@"new_window"];
[wc showWindow:self];
- (void)applicationWillTerminate:(NSNotification *)aNotification
// Insert code here to tear down your application
@end
我认为你可以将 Objective-C 语法更改为 Swift 语法。
【讨论】:
谢谢!但我没有使用故事板..如果我使用 xid 而不是故事板,你能告诉我它是如何工作的吗?【参考方案2】:#import "AppDelegate.h"
#import "Win.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
Win* win;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
// Insert code here to initialize your application
win = [[Win alloc] initWithWindowNibName:@"Win"];
[win showWindow:self];
- (void)applicationWillTerminate:(NSNotification *)aNotification
// Insert code here to tear down your application
@end
这样的代码并创建NSWindowController
的子类
【讨论】:
我尝试通过添加var aboutWindow: AboutWindowController!
并重新定义函数getAbout
像这样:func getAbout(sender: AnyObject) aboutWindow = AboutWindowController(windowNibName: "aboutWindow") aboutWindow.showWindow(self)
,但是当我点击“关于我的程序”时它挂起以上是关于使用 Swift 在 OS X 应用程序中打开新窗口的主要内容,如果未能解决你的问题,请参考以下文章
pathForResource 在 Mac OS X 控制台应用程序中返回 nil — Swift