这是 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()])
}
}
}
}
请注意,您是在玩火。出于某种原因,未指定像这样的内部结构。