2017-02-22 70 views
0

可選的值在我的自定義的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

回答

0

首先確認您的boardInfoDic

插座連接不爲空。當你做if let string = boardInfoDic?["description"]使用此

func updateItemAtIndexPath(_ indexPath: NSIndexPath) { 

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

} 
0

變量stringString類型是AnyObject型的不行。因此,如果您將string轉換爲String,則無法進行此類型轉換,結果返回nil。爲了從您的字典中獲取字符串,您需要使用類型AnyObject來訪問它。例如

if let string = boardInfoDic?["description"] 
     { 
      boardNameLabel.text = String(format: "%@", string as! String) 
     } 

一定要標記爲答案,如果它可以幫助你。

0

儘量選購的轉換

if let string = boardInfoDic?["description"] as? String { 
    boardNameLabel.text = String(format: "%@", string) 
} 
0

這爲我工作

if let string = boardInfoDic?["description"] as? String 
    { 
     boardNameLabel?.text = string 
    } 
相關問題