24

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?

2 Answers 2

66

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"
}
8
  • Thank you for the great clarification! It's working now.
    – Blaszard
    Jun 16, 2014 at 7:07
  • 1
    BTW, then what is the self.title for?
    – Blaszard
    Jun 16, 2014 at 9:36
  • 1
    NSViewController doesn't display the title. You can use this property to store a name for this particular VC instance for later use. (E.g. to provide a name for controls that initiate a transition to this VC - A popup or a list view etc...) Jun 16, 2014 at 10:06
  • 1
    Doesn't it need to be self.view.window!.title now?
    – Grimxn
    Apr 7, 2015 at 10:33
  • 2
    I would use optional chaining for the window, I try to avoid ! whenever possible. self.view.window?.title = "My Window". Also, it's important to place code accessing the window in viewDidAppear (as shown above) and not in viewDidLoad, as the window will still be nil there.
    – Ben Stahl
    Aug 7, 2017 at 20:21
1

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
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.