xcode Cocoa:如何在 Swift 的视图控制器中设置窗口标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24235815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:06:01  来源:igfitidea点击:

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

xcodecocoaswift

提问by Blaszard

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.

我尝试在 Xcode 6 中使用故事板和 Swift 的 Cocoa 应用程序进行构建。但是,当我尝试从内更改窗口的标题时NSViewController,以下代码不起作用。

self.title = "changed label"

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

当我在viewDidLoad()函数中编写上述代码时,生成的应用程序的标题仍然是window

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

此外,以下代码会导致错误,因为视图控制器没有window.

self.window.title = "changed label"

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

那么如何在基于故事板的 Cocoa 应用程序中以编程方式更改窗口的标题?

回答by Thomas Zoechling

There are 2 problems with your code:

您的代码有两个问题:

  • viewDidLoadis called beforethe view is added to the window
  • NSViewControllerdoes not have a window property
  • viewDidLoad将视图添加到窗口之前调用
  • NSViewController没有窗口属性

To fix the first one, you could override viewDidAppear(). This method is called afterthe 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

要修复第一个,您可以覆盖viewDidAppear(). 在视图完全转换到屏幕调用此方法。那时它已经被添加到一个窗口中。
要获得对窗口标题的引用,您可以通过视图访问视图控制器的窗口: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"
}

回答by Mike Zriel

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

这对我有用,currentDict 是从以前的 viewController 传递的 NSDictionary

var currentDict:NSDictionary?

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

}