我正在尝试从文件加载笔尖。
我有此代码,从这里
protocol NibLoadable {
static var nibName: String? { get }
static func createFromNib(in bundle: Bundle) -> Self?
}
extension NibLoadable where Self: NSView {
static var nibName: String? {
return String(describing: Self.self)
}
static func createFromNib(in bundle: Bundle = Bundle.main) -> Self? {
guard let nibName = nibName else { return nil }
var topLevelArray: NSArray? = nil
bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
guard let results = topLevelArray else { return nil }
// let views = Array<Any>(results).filter { $0 is Self }
// return views.last as? Self
let element = results[0] as? Self
return results[0] as? Self
}
}
结果有两个元素,一个nsview和nsapplication。
这里的问题是element
是零。评论的代码也给了我nil
。
我是Swift的新手。此Self
传递或在createFromNib
的最后一行中表示什么?
不能保证第一个对象是请求的视图。
使用first(where
并声明nibName
不可接受为要求。
protocol NibLoadable {
static var nibName: String { get }
static func createFromNib(in bundle: Bundle) -> Self?
}
extension NibLoadable where Self: NSView {
static var nibName: String {
return String(describing: Self.self)
}
static func createFromNib(in bundle: Bundle = Bundle.main) -> Self? {
var topLevelArray: NSArray? // Optionals are nil by default
bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
return topLevelArray?.first(where: { $0 is Self }) as? Self
}
}
几个小时后尝试使用不存在的文档,我随之而来,更简单。
func loadViewFromNib() {
var topLevelArray : NSArray?
let bundle = Bundle(for: type(of: self))
let nib = NSNib(nibNamed: .init(String(describing: type(of: self))), bundle: bundle)!
nib.instantiate(withOwner: self, topLevelObjects: &topLevelArray)
let myView = topLevelArray?.first(where: { $0 is NSView }) as? NSView
addSubview(myView!)
}
感谢@Vadian所做的所有努力。