Exc_Bad_Access从Xib加载CustomView时

时间:2017-12-16 11:43:33

标签: ios swift exc-bad-access iboutlet custom-view

CustomView中的IBOutlets将为零。

我创建了自定义视图(xib)。

请查看图片以获取更多信息。

class TextFieldView: UIView {

@IBOutlet var contentView: TextFieldView!
@IBOutlet weak var customTextField: UITextField!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var placeHolderLabel: UILabel!

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

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

override func awakeFromNib() {
    super.awakeFromNib()
}

func commonInit() 
{
let bundle = Bundle(for: type(of: self))
bundle.loadNibNamed("TextFieldView", owner: self, options: nil)
customTextField.backgroundColor = UIColor.green
NSLog("Called")
}

仍然使用exc_bad_access抛出错误。(在loadNibNamed代码行中)

2 个答案:

答案 0 :(得分:0)

您需要以下内容:

/// This view must be connected with the main view of the XIB.
@IBOutlet private var view: UIView!

/// This method is used when creating an `ApexView` with code.
override init(frame: CGRect)
{
    super.init(frame: frame)

    initView()
}

/// This method is called when instantiated from a XIB.
required init?(coder aDecoder: NSCoder)
{
    super.init(coder: aDecoder)

    initView()
}

private func initView()
{
    /// Fill in the name of your XIB. I assumed it `"TextFieldView"`.
    Bundle.main.loadNibNamed("TextFieldView", owner: self, options: nil)

    self.view.frame = CGRect(x: 0.0, y: 0.0, width: self.width, height: self.height)
    self.addSubview(self.view!)

    ...
}

答案 1 :(得分:0)

Swift 3版本

这是适合我的解决方案。确保IB中的文件对象具有分配给它的TextFieldView类(而不是UIView本身)。还要确保所有IBOutlet都连接到正确的位置,否则您可能会遇到麻烦。

class TextFieldView: UIView {

    @IBOutlet var contentView: TextFieldView!
    @IBOutlet weak var customTextField: UITextField!
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var placeHolderLabel: UILabel!


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

                commonInit()
            }

        //This lets us use TextFieldView in IB
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }

        private func commonInit() {

                 Bundle(for: TextFieldView.self).loadNibNamed("TextFieldView", owner: self, options: nil)
                //Positioning content so it fills view space
                contentView.frame = self.bounds
                contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
                addSubview(contentView)
            }