2017-04-06 74 views
-1

我有兩個tableview在同一Collectionviewcell。當我運行應用程序,它崩潰中的tableview中的cellForRowAtIndexPath,說:「致命錯誤:意外發現零而展開的可選值」它在tableview的cellforrowatindexpath中崩潰,說:「致命錯誤:意外地發現零,而解包可選值」

請在下面找到一些我的代碼 -

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
UITableViewCell { 

let cell = collectionView.dequeueReusableCell(withReuseIdentifier:  
reuseIdentifier, for: indexPathOfCollectionView as IndexPath) as! 
MyCustomCollectionViewCell 

if(tableView == cell.graphTableView){ 

let cell:CustomGraphTableViewCell = 
tableView.dequeueReusableCell(withIdentifier: "CustomGraphTableViewCell") as!  
CustomGraphTableViewCell 

return cell 
    } 
    else 
    { 
     let cell:MyCustomTableViewCell = 
tableView.dequeueReusableCell(withIdentifier: "MyCustomTableViewCell") as! 
MyCustomTableViewCell 
     cell.nameLabel.text = namesArray[indexPath.row] 
     return cell 

    } 
} 

誰能請建議解決方案。爲什麼會發生這種情況以及相同的解決方案?

+2

不能出隊'CollectionViewCell''在TableView'cellForRowAt'方法。 –

+0

你讓力量在這裏解開「as!」檢查你的所有單元格,因爲現在它的nil –

+0

@NiravD任何想法,那麼如果我沒有在那裏聲明collectionview單元,我怎樣才能訪問tableview? –

回答

2

在實現代碼如下UICollectionViewCell將無法​​正常工作,UICollectionViewCell是從UICollectionReusableViewUITableViewCell繼承不同的類是UICollectionViewCell不同的類,它是從UIViewNSCodingUIGestureRecognizerDelegate繼承的,所以在這裏,你必須只UITableView的電池使用爲你的tableview。否則它會崩潰。

當你的tableview委託方法返回一些值不能不null或0,那麼的tableview將執行的數據源方法,這意味着當你的tableview的委託方法有一定的價值的

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
UITableViewCell 

上述方法現在將開始執行當它發現

let cell = collectionView.dequeueReusableCell(withReuseIdentifier:  
reuseIdentifier, for: indexPathOfCollectionView as IndexPath) as! 
MyCustomCollectionViewCell 

上面的語句,它會崩潰。

這是

let cell:MyCustomTableViewCell = 
tableView.dequeueReusableCell(withIdentifier: "MyCustomTableViewCell") as! 
MyCustomTableViewCell 
     cell.nameLabel.text = namesArray[indexPath.row] 
     return cell 

只有把這個語句cellforRow數據源的方法下,它會相應工作。

感謝

+0

謝謝阿布舍克!是的,我從cellforrowatindexpath中刪除了collectionviewcell對象,並將標籤分配給tableview進行檢查,現在它工作正常:) –

+1

好的,:)快樂的Codding,如果我的建議爲你工作,那麼請接受並投票我的答案..謝謝: ) –

0

請檢查該行

cell.nameLabel.text = namesArray[indexPath.row] 

cell.nameLabel總是接受字符串值,首先轉換爲這樣的字符串值:

cell.nameLabel.text = namesArray[indexPath.row] as NSString 
相關問題