Swift 从 Nib 创建自定义视图

Swift create Custom View from Nib

我尝试使用 Nib 文件实现自定义加载器视图。但我得到一个错误 在 loadViewFromNib()

return nib.instantiate(withOwner: self, options: nil).first as? UIView.

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee6f3df98)

open class LoaderView: UIView {

@IBOutlet var loaderImage: UIImageView!    
@IBOutlet var contentView: UIView!

func xibSetup() {
    contentView = loadViewFromNib()
    contentView.frame = bounds
    contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
    addSubview(contentView)
}

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

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

func loadViewFromNib() -> UIView? {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "LoaderView", bundle: bundle)
    return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}

我在 viewDidLoad() 中将 VC 中的这个加载程序称为

let loader = LoaderView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view.addSubview(loader)

你在

中有递归
required public init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    xibSetup()
}

你在xibSetup()中调用loadViewFromNib(),它调用UINib(nibName: "LoaderView", bundle: bundle),那个调用required public init?(coder aDecoder: NSCoder)

developer.apple.com

你的代码很好,没有递归

请确保您有

1) 仔细检查您的 IBOUtlet 连接

2) 在文件所有者中添加了您的class


我已经创建了这个和你的代码一样

class CustomView: UIView {

    let nibName = "CustomView"
    @IBOutlet var view : UIView!

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

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

    func xibSetUp() {
        view = loadViewFromNib()
        view.frame = self.bounds
        view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        addSubview(view)
    }

    func loadViewFromNib() -> UIView {

        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "CustomView", bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as! UIView

    }

}

查看输出