首先該方法尚未在改變斯威夫特3。
loadNibNamed(_:owner:topLevelObjects:)
已經在macOS 10.8中引入,並出現在所有版本的Swift中。然而loadNibNamed(nibName:owner:options:)
已斯威夫特3.被丟棄
方法的簽名是
func loadNibNamed(_ nibName: String,
owner: Any?,
topLevelObjects: AutoreleasingUnsafeMutablePointer<NSArray>?) -> Bool
,所以你必須創建一個指針來獲得的意見陣列上的回報。
var topLevelObjects = NSArray()
if Bundle.main.loadNibNamed("CardView", owner: self, topLevelObjects: &topLevelObjects) {
let views = (topLevelObjects as Array).filter { $0 is NSView }
return views[0] as! NSView
}
編輯:我更新了答案,以可靠地過濾NSView
實例。
在斯威夫特4語法略有改變,並使用first(where
更高效:
var topLevelObjects : NSArray?
if Bundle.main.loadNibNamed(assistantNib, owner: self, topLevelObjects: &toplevelObjects) {
return topLevelObjects!.first(where: { $0 is NSView }) as? NSView
}
在一行上讓view = topLevelObjects [0] as! NSView - 我收到錯誤「無法將'NSApplication'類型的值(0x7fffd8201278)轉換爲'NSView'(0x7fffd8210048)。」 – Alex
調用此方法假定有一個包含視圖的nib/xib文件作爲頂級對象。 – vadian
謝謝,發現一個錯誤。 – Alex