在原型单元格上设置动态图像?
Set a dynamic image on prototype cell?
我想在 "Profile" 单元格上显示用户的图像。
为此,我应该使用解决配置文件加载的相同代码段。
首先我声明了一个UIImageView!
变量:
var accountimage: UIImageView!
然后,在我的 cellForRowAtIndexPath
中,我通过 UserDefaults
构造函数下载了 Avatar:
if indexPath.row == 1 {
cell.backgroundColor? = UIColor(red: 236/255,green: 239/255,blue: 240/255,alpha: 1)
let myFont: UIFont? = UIFont(name: "Avenir Next Condensed", size: 22.0)
if let aFont = myFont {
cell.textLabel?.font = aFont
//load account image
if UserDefaults.standard.object(forKey: "profile_avatar") != nil{
let decoded = UserDefaults.standard.object(forKey: "profile_avatar") as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded)
accountimage.image = decodedTeams as? UIImage
cell.imageView?.image = accountimage.image
} else
{
accountimage.image = #imageLiteral(resourceName: "user.png")
cell.imageView?.image = accountimage.image
}
}
}
调试器在 accountimage.image = decodedTeams as? UIImage
行说:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
Optional value
编辑
这是我的 Main.Storyboard
屏幕,以防万一:
也许你在这段代码上犯了一个小错误
let decoded = UserDefaults.standard.object(forKey: "profile_avatar") as! Data
**as!**表示强制转换但可能会失败。
我想在 "Profile" 单元格上显示用户的图像。 为此,我应该使用解决配置文件加载的相同代码段。
首先我声明了一个UIImageView!
变量:
var accountimage: UIImageView!
然后,在我的 cellForRowAtIndexPath
中,我通过 UserDefaults
构造函数下载了 Avatar:
if indexPath.row == 1 {
cell.backgroundColor? = UIColor(red: 236/255,green: 239/255,blue: 240/255,alpha: 1)
let myFont: UIFont? = UIFont(name: "Avenir Next Condensed", size: 22.0)
if let aFont = myFont {
cell.textLabel?.font = aFont
//load account image
if UserDefaults.standard.object(forKey: "profile_avatar") != nil{
let decoded = UserDefaults.standard.object(forKey: "profile_avatar") as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded)
accountimage.image = decodedTeams as? UIImage
cell.imageView?.image = accountimage.image
} else
{
accountimage.image = #imageLiteral(resourceName: "user.png")
cell.imageView?.image = accountimage.image
}
}
}
调试器在 accountimage.image = decodedTeams as? UIImage
行说:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
编辑
这是我的 Main.Storyboard
屏幕,以防万一:
也许你在这段代码上犯了一个小错误
let decoded = UserDefaults.standard.object(forKey: "profile_avatar") as! Data
**as!**表示强制转换但可能会失败。