从 nib 实例化 UIView 会导致无限循环问题

She*_*ary 4 xcode custom-controls nib swift swift3

我正在尝试使用我创建的自定义视图。

我使用笔尖实例化,但它会导致无限循环,我不知道如何修复。任何想法?

这是运行结果的图像:

在此输入图像描述

这是导致问题的代码:

// MARK:  - Init & Setup
// Needed for IBDesignable



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

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

func setup(){
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
    addSubview(view)
}

func loadViewFromNib() -> UIView{
    let bundle = Bundle(for:type(of: self))
    let nib = UINib(nibName: "LoginView", bundle: bundle)         // TEST: changin bundle from bundle-> nil

    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
    return view
}
Run Code Online (Sandbox Code Playgroud)

编辑:这是连接的图像

在此输入图像描述

谢谢 :)

Dan*_*ani 7

快速回答:\n由于 Xib 中的顶级视图已设置custom class为 YourCustomeView,因此 xib 加载过程loadViewFromNib将调用您的initWithCoder方法 \xe2\x9b\x94\xef\xb8\x8f\xe2\x99\xbd。

\n\n

快速修复:\n在 Xib 中,不要将视图的自定义类设置为 YourCustomeView,而是将 YourCustomeView 设置为The File OwnerXib 的自定义类。

\n\n

更多信息\n https://medium.com/@anandin02/loading-custom-views-in-ios-the-right-way-bedfc06a4fbd

\n