【问题标题】:IBDesignable crash EXC_BAD_ACCESS when attempting to call loadNibNamedIBDesignable 在尝试调用 loadNibNamed 时崩溃 EXC_BAD_ACCESS
【发布时间】:2016-02-24 01:08:08
【问题描述】:

我有一个名为DesignableControl 的基类。我在我的自定义视图中使用它,以便我可以看到它们在情节提要中呈现。这是基类:

public class DesignableControl: UIControl {

    private var view: UIView!

    override public init(frame: CGRect) {
        super.init(frame: frame)
        configureViewForStoryboard()
    }

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

    func configureViewForStoryboard() {
        if let nibView = NSBundle(forClass: self.dynamicType).loadNibNamed("\(self.dynamicType)", owner: self, options: nil).first as? UIView {
            view = nibView
        } else {
            Log("Error loading view for storyboard preview. Couldn't find view named \(self.dynamicType)")
            view = UIView()
        }
        view.frame = bounds
        view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
        backgroundColor = .clearColor()
        addSubview(view)
    }
}

这是我的子类StackedButton:

class StackedButton: DesignableControl {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
    @IBOutlet weak var label: UILabel!

    ...
}

上面的代码在我运行应用程序时运行并且看起来很好,但是,当我在情节提要中查看它时,它会在 DesignableControl 的下一行使用 EXC_BAD_ACCESS 使 Interface Builder 进程崩溃(为了清楚起见) :

func configureViewForStoryboard() {
    let bundle = NSBundle(forClass: self.dynamicType)
    print("bundle: \(bundle)")
    let nibArray = bundle.loadNibNamed("\(self.dynamicType)", owner: self, options: nil)
    print("nibArray: \(nibArray)") //<-- EXC_BAD_ACCESS

    ...
}

当我第一次编写这段代码时,它曾经可以工作,但似乎在最新版本的 Xcode(截至本文时为 7.2.1)中被破坏了。我做错了什么?

【问题讨论】:

  • 看起来在 IB 中运行时,loadNobNamed(...) 返回一个 nil。愚蠢的想法,但检查self.dynamicType 在两种情况下都解析为相同的名称。

标签: ios ibdesignable


【解决方案1】:

更新:

代码在运行时开始崩溃,因为视图设置不正确。事实证明,堆栈溢出问题是一个红鲱鱼。在设置之前访问@IBOutlets 的某些@IBDesignable 属性的子类中存在错误。这是根本问题。

之前:

@IBInspectable var text: String? {
    get { return label.text }
    set { label.text = newValue }
}

之后:

@IBInspectable var text: String? {
    get { return label?.text }
    set { label?.text = newValue }
}

原答案:

堆栈溢出™!!!

loadNibNamed() 正在调用其中一个构造函数,它正在调用 configureViewForStoryboard(),它正在调用其中一个构造函数,它正在调用 configureViewForStoryboard()。

我从init?(coder aDecoder: NSCoder) 中删除了对configureViewForStoryboard() 的调用,现在它似乎可以工作了。

【讨论】:

    猜你喜欢
    • 2015-10-19
    • 2023-03-03
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多