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

,我来自collectionViewcellForItemAt 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 enter image description here

+0

行更改为'如果让字符串= boardInfoDic?[ “说明”]作为?字符串“,然后简单地boardNameLabel.text =字符串。 –

+0

@NiravD更改代码后我也得到了同样的错误 – SriKanth

+0

@NiravD更新了这个问题,并参考了outlet,我从昨晚开始修复这个问题。 – SriKanth

首先确认您的boardInfoDic

插座连接不为空。当你做if let string = boardInfoDic?["description"]使用此

func updateItemAtIndexPath(_ indexPath: NSIndexPath) { 

       print(boardInfoDic) 
       boardNameLabel.text = String(self.boardInfoDic["description"]!) 

} 

变量stringString类型是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 
    }