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

China☆狼群 提交于 2020-05-25 04:05:22

问题


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?


回答1:


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



回答2:


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
    }

}


来源:https://stackoverflow.com/questions/24235815/cocoa-how-to-set-window-title-from-within-view-controller-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!