这就是我所拥有的:
NSWindow子类
import Cocoa import CoreLocation class TweetWindow: NSWindow { var locationManager: CLLocationManager! var geoCoder: CLGeocoder! @IBAction func tweetButtonPressed(sender:NSButton) { } func initialize() { self.titleVisibility = NSWindowTitleVisibility.Hidden; self.locationManager = CLLocationManager(); self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; self.locationManager.distanceFilter = 10; self.geoCoder = CLGeocoder(); } func windowWillShow() { if !self.visible { let systemAppearanceName = (NSUserDefaults.standardUserDefaults().stringForKey("AppleInterfaceStyle") ?? "Light").lowercaseString; let systemAppearance = systemAppearanceName == "dark" ? NSAppearance(named: NSAppearanceNameVibrantDark) : NSAppearance(named: NSAppearanceNameVibrantLight); self.appearance = systemAppearance; self.locationManager.startUpdatingLocation(); } } func windowWillClose() { self.locationManager.stopUpdatingLocation(); } }
NSWindowController子类:
import Cocoa class TweetWindowController: NSWindowController { var tweetWindow: TweetWindow { return self.window as! TweetWindow; } override func windowDidLoad() { super.windowDidLoad() self.tweetWindow.initialize() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } override func showWindow(sender: AnyObject?) { self.tweetWindow.windowWillShow() super.showWindow(sender) } }
当然,我也有一个包含我窗口的.xib文件.它被称为“TweetWindow.xib”.
现在,到目前为止,这应该没问题.
在我的AppDelegate.swift中,我执行以下操作:
@NSApplicationMain class AppDelegate: NSObject,NSApplicationDelegate { var tweetWindowController:TweetWindowController!; func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application tweetWindowController = TweetWindowController(windowNibName: "TweetWindow"); } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func showTweetWindowInternal() { NSApp.activateIgnoringOtherApps(true); tweetWindowController.showWindow(nil); } @IBAction func showTweetWindow(sender: AnyObject) { showTweetWindowInternal(); } @IBAction func quitApp(sender: AnyObject) { NSApplication.sharedApplication().terminate(self); } }
我的问题如下:
当我尝试单击与IBAction相关联的按钮以显示窗口时,会抛出异常:
var tweetWindow:TweetWindow {return self.window as! TweetWindow; }
它说致命错误:在展开Optional值时意外发现nil,因此窗口为零.
为什么那里的窗户没有?我试图过早地获取价值还是什么?
这是一些照片:
谢谢.