0

我有一个名为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!

    ...
}

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

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)中被破坏了。我究竟做错了什么?

4

1 回答 1

0

更新:

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

前:

@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()

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

于 2016-02-24T16:58:55.770 回答