2017-08-29 2 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'の中の3行全てにブレークポイントを置いて、 'reloadData'のAppdelegateファイルにリダイレクトしました。質問に既にあるもの以外は何も表示しませんでした。 –

+0

__exception breakpoint__を私はすでに、通常のブレークポイントだけでなく、言及した。例外ブレークポイントは、例外がスローされたときに実行を停止し、例外の正確な原因を調査できるようにします。 –

答えて

1

コレクションビューのセルinsertingまたはdeletingより先にデータソースを変更する必要があります。

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) 
関連する問題