2017-08-29 73 views
0

我有這個代碼斯威夫特將在uicollectionview細胞給我一個錯誤

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
{ 
    return comments.count 
} 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = commentSection.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CommentCell 
     return cell 
} 

,我已經低於這個功能,這將插入細胞

DispatchQueue.main.async{ 
        let indexPath = IndexPath(row: self.comments.count, section: 0) 
        self.commentSection.insertItems(at: [indexPath]) 
        self.commentSection.reloadData() 
} 

但每當我運行這段代碼將打印此錯誤

libc++abi.dylib: terminating with uncaught exception of type NSException 

並將我重定向到AppDelegate文件。儘管錯誤非常清晰地寫入10我無法理解問題

+0

在調試器中設置一個異常斷點,幷包含實際錯誤和導致它在你的問題中的行。 –

+0

@DávidPásztor我把一個斷點在所有三行''DispatchQueue裏面,它重定向我的appdelegate上'reloadData文件'和 –

+0

你需要建立一個__exception breakpoint__作爲未打印,除了那些已經在這個問題什麼我已經提到過,不僅僅是一個正常的斷點。拋出異常時異常斷點會暫停執行,並讓您調查異常的確切原因。 –

回答

1

您需要先修改數據源,然後才能從collectionView的insertingdeleting單元格中修改數據源。

self.collectionView?.performBatchUpdates({ 
    let indexPath = IndexPath(row: self.comments.count, section: 0) 
    comments.append(your_object) //add your object to data source first 
    self.collectionView?.insertItems(at: [indexPath]) 
}, completion: nil) 
+0

感謝它的工作! –

+0

@ louis-ck:很高興它做了:)總是歡迎哥們:) –

0

請確保您插入項目集合視圖

0

performBatchUpdates之前也插入附加對象在comments陣列建議的方式插入的CollectionView項目。首先更新數據源,然後致電performBatchUpdates在收集視圖中插入新項目。

//Update DataSource 
let newComment = "This is new comment" 
comments.append(newComment) 

let indexPath = IndexPath(item: self.comments.count - 1, section: 0) 
var indexPaths: [IndexPath] = [indexPath] 

// finally update the collection view 
collectionView.performBatchUpdates({() -> Void in 
    collectionView.insertItems(at: indexPaths) 
}, completion: nil)