的UILabel设置文本意外地发现零而展开斯威夫特3
问题描述:
可选的值在我的自定义的CollectionView细胞我有的UILabel设置文本意外地发现零而展开斯威夫特3
@IBOutlet weak var boardNameLabel: UILabel!
var boardInfoDic: Dictionary? = [String : AnyObject]()
func updateItemAtIndexPath(_ indexPath: NSIndexPath) {
if let string = boardInfoDic?["description"]
{
boardNameLabel.text = String(format: "%@", string as! String)
}
}
,我来自collectionView
cellForItemAt indexPath:
作为
let boardsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: KBoardsCollectionViewCellIdentifier, for: indexPath) as! BoardsCollectionViewCell
boardsCollectionViewCell.boardInfoDic = self.boardsDataArray?[indexPath.item] as Dictionary<String, AnyObject>?
boardsCollectionViewCell.updateItemAtIndexPath(indexPath as NSIndexPath)
,但我将数据发送到boardInfoDic我越来越fatal error: unexpectedly found nil while unwrapping an Optional value
,我被尝试了多种方式,但没有用。我该如何解决这个问题?与UICollectionViewCell
答
首先确认您的boardInfoDic
插座连接不为空。当你做if let string = boardInfoDic?["description"]
使用此
func updateItemAtIndexPath(_ indexPath: NSIndexPath) {
print(boardInfoDic)
boardNameLabel.text = String(self.boardInfoDic["description"]!)
}
答
变量string
是String
类型是AnyObject
型的不行。因此,如果您将string
转换为String
,则无法进行此类型转换,结果返回nil。为了从您的字典中获取字符串,您需要使用类型AnyObject
来访问它。例如
if let string = boardInfoDic?["description"]
{
boardNameLabel.text = String(format: "%@", string as! String)
}
一定要标记为答案,如果它可以帮助你。
答
尽量选购的转换
if let string = boardInfoDic?["description"] as? String {
boardNameLabel.text = String(format: "%@", string)
}
答
这为我工作
if let string = boardInfoDic?["description"] as? String
{
boardNameLabel?.text = string
}
行更改为'如果让字符串= boardInfoDic?[ “说明”]作为?字符串“,然后简单地boardNameLabel.text =字符串。 –
@NiravD更改代码后我也得到了同样的错误 – SriKanth
@NiravD更新了这个问题,并参考了outlet,我从昨晚开始修复这个问题。 – SriKanth