@IBDesignable crashing agent

2019-01-13 11:51发布

When I write my own UIButton-extended class and make it @IBDesignable, I receive two errors in Interface Builder, namely:

  • Main.storyboard: error: IB Designables: Failed to update auto layout status: The agent crashed because the fd closed
  • Main.storyboard: error: IB Designables: Failed to render instance of RandjeUIButton: The agent crashed

Here is my code:

import UIKit

@IBDesignable
class RandjeUIButton: UIButton {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.backgroundColor = UIColor.blackColor()
    }
}

I am working in Xcode 7 beta 2 on OS X 10.11 beta 2. (Running in VM)

9条回答
淡お忘
2楼-- · 2019-01-13 12:42

I found something really important when using an UIImage in any class marked @IBDesignable. The classic UIImage init would crash the agent:

let myImage = UIImage(named: String) // crash the agent

The solution is to use this init method of UIImage:

let myImage = UIImage(named: String, in: Bundle, compatibleWith: UITraitCollection)

Working code example:

let appBundle = Bundle(for: type(of: self))
let myImage = UIImage(named: "myImage", in: bundle, compatibleWith: self.traitCollection))

Where self is your class with the @IBDesignable keyword. Xcode 9.4, Swift 4.1

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-13 12:45

Xcode's Interface Builder requires that you implement both or neither initializers for @IBDesignable classes to render properly in IB.

If you implement required init(coder aDecoder: NSCoder) you'll need to override init(frame: CGRect) as well, otherwise "the agent will crash" as seen in the errors thrown by Xcode.

To do so add the following code to your class:

override init(frame: CGRect) {
    super.init(frame: frame)
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-13 12:46

There are a myriad of problems that can cause this. Fire up Console, and look for the crash report IBDesignablesCocoaTouch...

I just sorted out a problem with a 3rd party designable which had issues with the valueForKey semantics.

查看更多
登录 后发表回答