如何使用Swift 2从xib加载自定义UIView?

时间:2015-12-07 19:49:43

标签: ios swift xib

任务是创建自定义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,但我不知道如何执行此操作。

2 个答案:

答案 0 :(得分:1)

  

尝试

let yourView = NSBundle.mainBundle().loadNibNamed("youViewNibName", owner: self, options: nil).first as! YourView

ViewController类中执行此操作,然后您可以使用编码器访问所需init中的视图,您应该在其中调用xibSetup()

答案 1 :(得分:0)

是否正确,您的班级名为 CustomView ,并且您正在加载 CustomView.xib ,其中xib中的视图类是 CustomView

如果是这样,你可能不明白你在做什么