尝试创建 UIImage returns:在展开可选值时意外发现 nil
Trying to create UIImage returns: unexpectedly found nil while unwrapping an Optional value
我有以下代码,每一行都有一个断点。它命中了以 var image : UIImage
开头的行,然后它因 nil 错误而崩溃。我有一个名为 Saturation.png 的文件。我已经尝试过不使用扩展名以及使用 named
而不是 contentsOfFile
我尝试的任何事情都不会越过那条线。
func addSubviews() {
if(filter != nil) {
var image : UIImage = UIImage(contentsOfFile: "Saturation.png")!
let view = UIImageView(image: image)
contentView.addSubview(view)
let filterNameLabel = UILabel(frame: CGRectMake(0, 66, 66, 20))
filterNameLabel.text = filter.name!.stringByReplacingOccurrencesOfString("Amount", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
filterNameLabel.textAlignment = .Center
filterNameLabel.textColor = UIColor(white: 0.9, alpha: 1.0)
filterNameLabel.highlightedTextColor = tintColor
filterNameLabel.font = UIFont.systemFontOfSize(12)
contentView.addSubview(filterNameLabel)
}
}
contentsOfFile:
需要图像的完整路径,而不仅仅是文件名,它不会为您进行搜索,因为该搜索可能涉及大量目录和文件。您需要获取完整路径,可能使用 NSBundle
,具体取决于文件所在的 Nd。
我有以下代码,每一行都有一个断点。它命中了以 var image : UIImage
开头的行,然后它因 nil 错误而崩溃。我有一个名为 Saturation.png 的文件。我已经尝试过不使用扩展名以及使用 named
而不是 contentsOfFile
我尝试的任何事情都不会越过那条线。
func addSubviews() {
if(filter != nil) {
var image : UIImage = UIImage(contentsOfFile: "Saturation.png")!
let view = UIImageView(image: image)
contentView.addSubview(view)
let filterNameLabel = UILabel(frame: CGRectMake(0, 66, 66, 20))
filterNameLabel.text = filter.name!.stringByReplacingOccurrencesOfString("Amount", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
filterNameLabel.textAlignment = .Center
filterNameLabel.textColor = UIColor(white: 0.9, alpha: 1.0)
filterNameLabel.highlightedTextColor = tintColor
filterNameLabel.font = UIFont.systemFontOfSize(12)
contentView.addSubview(filterNameLabel)
}
}
contentsOfFile:
需要图像的完整路径,而不仅仅是文件名,它不会为您进行搜索,因为该搜索可能涉及大量目录和文件。您需要获取完整路径,可能使用 NSBundle
,具体取决于文件所在的 Nd。