Interface builder agent crashes when accessing @IB

2019-06-25 18:56发布

问题:

I'm implementing a custom view by subclassing UIView and using @IBInspectable for some of my variables. Two of them are UIImage. If I try to access one of them in the code, the interface builder crashes with the following message:

file:///PathToMyProject/MyProject/Pod/Classes/UI/View/MyView.xib: error: IB Designables: Failed to update auto layout status: The agent crashed

and

file:///PathToMyProject/MyProject/Pod/Classes/UI/View/MyView.xib: error: IB Designables: Failed to render instance of MyView: The agent crashed

Everything runs fine on simulator and device. Here's how you can reproduce it, assumed image_one.png is in the assets:

import UIKit

@IBDesignable
class MyView: UIView {

    @IBInspectable
    var anImage: UIImage = UIImage(named: "image_one")!

}

In fact the interface builder agent crashes at initializing this variable. If you write var anImage: UIImage! = UIImage(named: "image_one"), then the agent crashes when accessing this variable (as stated above).

Any ideas?

回答1:

You do not have to set you image in inspector in IB heres a solution purely in code.

let bundle = Bundle(for: self.classForCoder)
image = UIImage(named: "your_image.png", in: bundle, compatibleWith: self.traitCollection)!
self.setImage(image, for: .normal) 


回答2:

The problem is that paths to images are different in Interface Builder than they are in your app, so IB is dereferencing a nil image. You can fix this by using optionals and then setting the image in the Attributes inspector in IB.

Here's the updated code:

import UIKit

@IBDesignable
class MyView: UIView {

    @IBInspectable
    var anImage: UIImage? = UIImage(named: "image_one")

}


回答3:

I have similar error using ibinspectable UIImage. I used image literal as initial value and that cause the error. I solved it by removing that image literal and changed to UIImage:named:.

This caused error:

@IBInspectable var _iconImage: UIImage? = #imageLiteral(resourceName: "ic_arrow_dropdown") {
    didSet { iconImageView.image = _iconImage }
}

_

Solved with:

@IBInspectable var _iconImage: UIImage? = UIImage(named: "ic_arrow_dropdown") {
    didSet { iconImageView.image = _iconImage }
}

_

*I know OP didn't use image literal. Just in case somebody need it.