[英]How to load custom UIView from xib using Swift 2?
The task is to create custom UIView that loads UI from .xib file using Swift. 任务是创建自定义UIView,以使用Swift从.xib文件加载UI。 How do I do that?
我怎么做?
I tried to do that using the code: 我尝试使用代码来做到这一点:
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
}
}
It runs, but crashes with EXC_BAD_ACCESS and shows me the message: 它运行,但是崩溃与EXC_BAD_ACCESS并显示以下消息:
warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.
Actually, I need to translate code given here http://qnoid.com/2013/03/20/How-to-implement-a-reusable-UIView.html to Swift 2.0, but I have no idea how to do this. 实际上,我需要将此处提供的代码http://qnoid.com/2013/03/20/How-to-implement-a-reusable-UIView.html转换为Swift 2.0,但是我不知道该怎么做。
Try
尝试
let yourView = NSBundle.mainBundle().loadNibNamed("youViewNibName", owner: self, options: nil).first as! YourView
Do it in your ViewController class , then you can access the view in required init with coder, where you should call xibSetup()
. 在ViewController类中执行此操作,然后可以使用编码器访问必需的init中的视图,在此应调用
xibSetup()
。
Is it correct, that your class is called CustomView and you're loading CustomView.xib where the class for the view in xib is CustomView ? 是正确的,您的类称为CustomView并且正在加载CustomView.xib ,而xib中视图的类是CustomView吗?
If that is so you probably do not understand what you're doing 如果是这样,您可能不了解自己在做什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.