无法从.xib文件加载UIView

时间:2016-09-03 16:27:23

标签: swift uiview xib

我正在尝试从XIB文件加载UIView,但它给了我这个错误:

  

致命错误:init(编码器:)尚未实现:file / Users / Skole-Pc / Desktop / IOS-Apps / CSGO Quiz Battle / AlertView.swift,第397行

这是我的XIB文件:

这是与XIB文件链接的类:

class HelpAlert: UIView {

    @IBOutlet var help1: UIButton!
    @IBOutlet var help2: UIButton!
    @IBOutlet var help3: UIButton!
    @IBOutlet var cancel: UIButton!

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    @IBAction func help1Action(sender: AnyObject) {
        let action1 = self.action1
        // deliberately set to nil just in case there is a self reference
        self.action1 = nil
        guard let block = action1 else { return }
        block()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }

}

这样我就可以尝试将HelpAlert添加到ViewController

if let alert = NSBundle.mainBundle().loadNibNamed("HelpAlert", owner: self, options: nil).first as? HelpAlert {
    alert.frame = CGRect(x: CGRectGetMidX(view.bounds), y: CGRectGetMidY(view.bounds), width: view.bounds.width * 0.9, height: view.bounds.width * 0.9 * (750/650))

    view.addSubview(alert)
}

并且当它给我错误时,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

生成错误,因为调用了fatalError()。删除此方法并使用编码器调用超级版本的init以获得正确的行为:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
 }