我试图弄清楚如何使用xib文件创建自定义视图.
在此 question中,使用下一个方法.
在此 question中,使用下一个方法.
NSBundle.mainBundle().loadNibNamed("CardView",owner: nil,options: nil)[0] as! UIView
Cocoa具有相同的方法,但是,这个方法在swift 3到loadNibNamed(_:owner:topLevelObjects:)中已经改变,它返回Bool,并且之前的代码生成“Type Bool没有下标成员”错误,这很明显,因为返回类型是Bool.
所以,我的问题是如何从Swift 3中的xib文件加载视图
首先,Swift 3中没有改变该方法.
loadNibNamed(_:owner:topLevelObjects :)已经在macOS 10.8中引入,并且存在于所有版本的Swift中.但是,在Swift 3中删除了loadNibNamed(nibName:owner:options :).
该方法的签名是
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实例.
在Swift 4中,语法略有改变并首先使用(其中效率更高:
var topLevelObjects : NSArray? if Bundle.main.loadNibNamed(assistantNib,topLevelObjects: &topLevelObjects) { return topLevelObjects!.first(where: { $0 is NSView }) as? NSView }
原文地址:https://www.jb51.cc/swift/318997.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。