I have two different cells types one is for comments and the other one for replies. I'm trying to render them in the same collectionView and then maybe grouping them like so: each comment with a certain id to have under it its replies. However, with any attempt, I failed.
How would you go about it?
private var comments = [Comment]()
private var replies = [Reply]()
var items: [Any] = []
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// let item = items[indexPath.item]
var item = items[indexPath.item]
if item is Comment.Type {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CommentCell.cellId, for: indexPath) as! CommentCell
cell.comment = items[indexPath.item] as? Comment
print(item)
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RepliesCell.cellId, for: indexPath) as! RepliesCell
cell.reply = items[indexPath.item] as? Reply
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let item = items[indexPath.item]
if item is CommentCell.Type {
let dummyCell = CommentCell(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 50))
dummyCell.comment = items[indexPath.item] as? Comment
dummyCell.layoutIfNeeded()
let targetSize = CGSize(width: view.frame.width, height: 250)
let estimatedSize = dummyCell.systemLayoutSizeFitting(targetSize)
let height = max(40 + 8 + 8, estimatedSize.height)
return CGSize(width: view.frame.width, height: height)
} else {
let dummyCell = RepliesCell(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 50))
dummyCell.reply = items[indexPath.item] as? Reply
dummyCell.layoutIfNeeded()
let targetSize = CGSize(width: view.frame.width, height: 250)
let estimatedSize = dummyCell.systemLayoutSizeFitting(targetSize)
let height = max(40 + 8 + 8, estimatedSize.height)
return CGSize(width: view.frame.width, height: height)
}
}
}
from Multiple Cells for Comments and Reply in a CollectionView
No comments:
Post a Comment