[英]How to load custom UIView from xib using Swift 2?
任务是创建自定义UIView,以使用Swift从.xib文件加载UI。 我怎么做?
我尝试使用代码来做到这一点:
import UIKit
@IBDesignable class CustomView: UIView {
var view: UIView!
@IBOutlet weak var label: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "CustomView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
它运行,但是崩溃与EXC_BAD_ACCESS并显示以下消息:
warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.
实际上,我需要将此处提供的代码http://qnoid.com/2013/03/20/How-to-implement-a-reusable-UIView.html转换为Swift 2.0,但是我不知道该怎么做。
尝试
let yourView = NSBundle.mainBundle().loadNibNamed("youViewNibName", owner: self, options: nil).first as! YourView
在ViewController类中执行此操作,然后可以使用编码器访问必需的init中的视图,在此应调用xibSetup()
。
是正确的,您的类称为CustomView并且正在加载CustomView.xib ,而xib中视图的类是CustomView吗?
如果是这样,您可能不了解自己在做什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.