简体   繁体   中英

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

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?

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"
}

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
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM