Swift Class 变量崩溃界面生成器实时渲染

Swift Class Variable Crashing Interface Builder Live Rendering

在 Swift 中,我通过 subclassing UIView 创建了一个自定义视图:

@IBDesignable class HandView: UIView {

var view:UIView!
var settings:AppSettings?

@IBOutlet weak var c1ImageView: UIImageView!
@IBInspectable var c1Image:UIImage? { didSet { self.c1ImageView?.image = self.c1Image } }

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    //self.settings = AppSettings.sharedInstance
    self.xibSetup()
  }
}

当我将此视图添加到故事板时,实时渲染按预期工作。一旦我取消注释该行:

//self.settings = AppSettings.sharedInstance

实时渲染崩溃 - 我收到以下错误消息:

error: IB Designables: Failed to render instance of BetView: Rendering the view took 
error: IB Designables: Failed to render instance of HandView: The designables agent 
crashed

应用程序编译并正常运行。唯一受影响的是实时渲染。 AppSettings class 是单例:

class AppSettings {

//This makes AppSettings a singleton
class var sharedInstance: AppSettings {
    struct Static {
        static let instance: AppSettings = AppSettings()
    }
    return Static.instance
}

private let settings = NSUserDefaults.standardUserDefaults()

init () {
    //Load default values from the plist file
    let settingsBundleURL = NSBundle.mainBundle().pathForResource("Defaults", ofType: "plist")
    let settingsDefaults = NSDictionary (contentsOfFile: settingsBundleURL!)
    self.settings.registerDefaults(settingsDefaults!)
}

我不确定它为什么会窒息,也不知道该怎么办。我不想停止使用实时渲染,因为它对我的项目开发非常有用。

您需要在 HandView

中覆盖 init(frame: CGRect)
override init(frame: CGRect) {
        super.init(frame: frame)
        self.settings = AppSettings.sharedInstance
        self.xibSetup()
}

并修复 AppSettings class。这行代码来自 AppSettings init() 方法

NSBundle.mainBundle().pathForResource("Defaults", ofType: "plist")

returns 可选值。所以在使用之前需要使用optional binding判断settingsBundleURL是否包含value

 init () {
    //Load default values from the plist file
    let settingsBundleURL = NSBundle.mainBundle().pathForResource("Defaults", ofType: "plist")
    if let url = settingsBundleURL {
       let settingsDefaults = NSDictionary (contentsOfFile: settingsBundleURL!)
       self.settings.registerDefaults(settingsDefaults!)
    }
 }