Hello, I'm building chat app, and also using CoreData to store messages.
I have rotated my collectionView, so that it looks like it's going bottom to up.
I have rotated my collectionView in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
msgsCollectionView.delegate = self
msgsCollectionView.dataSource = self
//observeUserMessages()
//rotate collectionView 180º
msgsCollectionView.transform = CGAffineTransform.init(rotationAngle: (-(CGFloat)(Double.pi)))
//move scroll indicator from right to left
msgsCollectionView.scrollIndicatorInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: msgsCollectionView.bounds.size.width - 7)
attemptFetch()
}
Then, I have rotated each cell in cellForRowAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let message = controller.object(at: indexPath)
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MessageCell", for: indexPath) as? MessageCell {
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
if let messageText = message.text {
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.darkGray], context: nil)
if !message.isSender {
cell.msgTextView.frame = CGRect(x: 8, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 18)
cell.textBubbleView.frame = CGRect(x: 0, y: 0, width: estimatedFrame.width + 16 + 8, height: estimatedFrame.height + 20)
} else {
cell.msgTextView.frame = CGRect(x: collectionView.frame.width - estimatedFrame.width - 16 - 8, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 18)
cell.textBubbleView.frame = CGRect(x: collectionView.frame.width - estimatedFrame.width - 16 - 8 - 8, y: 0, width: estimatedFrame.width + 16 + 8, height: estimatedFrame.height + 20)
}
}
cell.configureCell(msg: message)
return cell
} else {
return MessageCell()
}
My problem is when I send a new message, the cells get reload and animated again to rotate 180º
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if type == .insert {
blockOperations.append(BlockOperation(block: {
self.msgsCollectionView.insertItems(at: [newIndexPath!])
}))
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if self.controller.fetchedObjects!.count > 0 {
self.msgsCollectionView.reloadData()
}
}
Please check the output:
How do I avoid cell layout effect??