Cocoa:如何设置窗口标题?

时间:2012-02-23 04:29:05

标签: objective-c cocoa

我有一个Cocoa应用程序,其中包含使用NSWindowController的子类创建的辅助窗口。我想设置窗口标题。记录的方法调用是setTitle:。我在窗口控制器中调用了它,如下所示:

- (void)windowDidLoad
{
    // set window title
    [[self window] setTitle:@"test string"]; 
}

这不会影响窗口的标题。

有什么建议吗?

5 个答案:

答案 0 :(得分:18)

您可以将您的窗口与IBOutlet连接,然后更改您的代码:

[[self window] setTitle:@"test string"];

对此:

[yourWindow setTitle:@"test string"];

完整代码例如:

·H

IBOutlet NSWindow *yourWindow; //Don't forget to connect window to this

的.m

-(void)awakeFromNib {
    [yourWindow setTitle:@"test string"];
}


<小时/> 当然,您无法以编程方式更改标题:

可以在属性检查器中更改标题:

enter image description here

答案 1 :(得分:5)

NSWindowController类引用表明要自定义标题,您应该覆盖windowTitleForDocumentDisplayName:方法。

答案 2 :(得分:3)

我只是用

self.window?.title = "Some String"

我在哪里创建窗口。

答案 3 :(得分:0)

在Swift中,这可以通过以下方式完成:someOutlet.title = "New Title"

以下是一个存在于窗口控制器类中的示例:

@IBOutlet weak var contentOutlet: NSWindow!

override func windowDidLoad() {
    super.windowDidLoad()

    contentOutlet.title = "New Title"
}

同样,请记住将插座连接到窗口,或者只是将插座从窗口拖到窗口控制器类。

答案 4 :(得分:0)

在将标题绑定到所选对象文件名时,使用最新的Xcode的基于非文档的应用程序存在相同的问题。只要没有选择,标题就会显示为“ Untitled”(无标题),这在应用程序中毫无意义。

因此,我在NSWindowController中创建了两个属性-一个属性绑定到所选对象的文件名,另一个属性绑定到Window标题。

在绑定到所选对象的属性的didSet {}方法中,我检查nil值并将title属性设置为应用程序名称。如果不是nil,则将属性设置为所选对象的文件名。

class WindowController: NSWindowController {

    /// Bind this to the controllers selected objects filename property
        @objc dynamic var filename: String? {
            didSet {
                if let name = filename {
                    title = name
                } else {
                    title = "IAM2 - no selection"
                }
            }
            
        }
        /// Bind this to the windows title
        @objc dynamic var title: String = "IAM2"


     override func windowDidLoad() {
    super.windowDidLoad()
    
    
    
    self.bind(NSBindingName(rawValue: "filename"),
              to: self.controller,
              withKeyPath: "selectedObject.filename",
              options: nil)
    
    self.window?.bind(NSBindingName(rawValue: "title"),
              to: self,
              withKeyPath: "title",
              options: nil)
    
    self.window?.bind(NSBindingName(rawValue: "subtitle"),
              to: controller,
              withKeyPath: "rootPath",
              options: nil)
    
}

}
相关问题