繁体   English   中英

Swift类变量崩溃Interface Builder实时渲染

[英]Swift Class Variable Crashing Interface Builder Live Rendering

在Swift中,我通过子类化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 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类。 这行代码来自AppSettings init()方法

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

返回可选值。 因此,在使用settingsBundleURL之前,您需要使用可选绑定来确定它是否包含值。

 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!)
    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM