Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa: How to set window title from within view controller in Swift?

Tags:

xcode

swift

cocoa

I've tried to build on a Cocoa app which uses storyboard and Swift in Xcode 6. However, when I tried to alter the title of window from within NSViewController, the following code doesn't work.

self.title = "changed label"

When I wrote the above code in viewDidLoad() function, the resultant app's title still remains window.

Also, the following code causes an error, since View Controller doesn't have such property as window.

self.window.title = "changed label"

So how can I change the title of window programmatically in Cocoa app which is built on storyboard?

like image 444
Blaszard Avatar asked Jun 16 '14 02:06

Blaszard


2 Answers

There are 2 problems with your code:

  • viewDidLoad is called before the view is added to the window
  • NSViewController does not have a window property

To fix the first one, you could override viewDidAppear(). This method is called after the view has fully transitioned onto the screen. At that point it is already added to a window.
To get a reference to the window title, you can access a view controller's window via its view: self.view.window.title

Just add the following to your view controller subclass, and the window title should change:

override func viewDidAppear() {
    super.viewDidAppear()
    self.view.window?.title = "changed label"
}
like image 94
Thomas Zoechling Avatar answered Nov 06 '22 04:11

Thomas Zoechling


This worked for me, currentDict is NSDictionary passed from previous viewController

var currentDict:NSDictionary?

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    if let myString:String = currentDict?["title"] as? String {
        self.title = myString
    }

}
like image 22
Mike Zriel Avatar answered Nov 06 '22 04:11

Mike Zriel