这里是一个在Swift中的解决方案,它已经很晚了,我很累,所以这可能不是最优的,但它的工作原理是
首先,这是一个功能,可以在层次结构中查找视图,并可以跳过特定的视图。 (这是有用的,如果我们正在经历window.contentView.superview.subviews
搜索,我们希望忽略contentView
你自己的看法)
func findViewInSubview(subviews: [NSView], #ignoreView: NSView, test: (NSView) -> Bool) -> NSView? {
for v in subviews {
if test(v) {
return v
} else if v != ignoreView {
if let found = findViewInSubview(v.subviews as [NSView], ignoreView: ignoreView, test) {
return found
}
}
}
return nil
}
这里是你将如何使用它,例如从NSViewController
子类。请注意,当窗口变得可见时,你需要做到这一点,所以你不能在viewDidLoad
。
override func viewDidAppear() {
if let windowContentView = view.window?.contentView as? NSView {
if let windowContentSuperView = windowContentView.superview {
let titleView = findViewInSubview(windowContentSuperView.subviews as [NSView], ignoreView: windowContentView) { (view) -> Bool in
// We find the title by looking for an NSTextField. You may
// want to make this test more strict and for example also
// check for the title string value to be sure.
return view is NSTextField
}
if let titleView = titleView as? NSTextField {
titleView.attributedStringValue = NSAttributedString(string: "Hello", attributes: [NSForegroundColorAttributeName: NSColor.redColor()])
}
}
}
}
请注意您正在玩火。这样的内部没有具体说明是有原因的。
我懒得试试这个,但我不知道你会得到什么,如果你有窗口的内容视图,并要求它的超级视图。也许你会得到零,或者你会得到一个包含其他隐藏事物的根视图。 – JWWalker
你得到一个名为NSThemeView的私有NSView子类。它确实包含了一些关于窗口关闭,最小化和最大化按钮的私人视图,但是我没有看到如何在不使用私有API的情况下访问标题。 – iain
有一篇由Matt Gallagher撰写的关于自定义窗口的文章,您应该能够在那里找到一些信息。 http://www.cocoawithlove.com/2008/12/drawing-custom-window-on-mac-os-x.html – Michael