Проблемы с констрейнтами в UIKit

Почему при появлении клавиатуры и скроллинге UICollectionView начинают расползаться ячейки? Если можно, то хотелось бы подробный ответ, т.к. я только начинаю осваиваться с разработкой под iOS и многие вещи в UIKit для меня, мягко говоря, совершенно неочевидные.

import UIKit

struct MessageItem {
    var message: String
    var role: MessageRole
}

enum MessageRole {
    case Sender
    case Receiver
}

class MessageCell: UICollectionViewCell {
    
    let customView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    let messageLabel: UIMessageView = {
        let label = UIMessageView()
        label.font = .systemFont(ofSize: 17, weight: .regular)
        label.numberOfLines = 0
        label.sizeToFit()
        label.insets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        label.textColor = .white
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        messageLabel.layer.masksToBounds = true
        messageLabel.layer.cornerRadius = 5
        
        messageLabel.backgroundColor = .systemBlue
        addSubview(messageLabel)
        
        contentView.translatesAutoresizingMaskIntoConstraints = false
        
        contentView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true
        contentView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        contentView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        contentView.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true
        
        NSLayoutConstraint.activate([
            messageLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0),
            messageLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0),
            messageLabel.widthAnchor.constraint(lessThanOrEqualToConstant: UIScreen.main.bounds.width - 50),
        ])

    }
    
    func isSender() {
        messageLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true
    }
    
    func isReceiver() {
        messageLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10).isActive = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class UIMessageView: UILabel {
    
    var insets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: insets))
    }
    
    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        
        let width = size.width + insets.left + insets.right
        let height = size.height + insets.top + insets.bottom
        
        return CGSize(width: width, height: height)
    }
}

class DialogViewController: UIViewController {
    
    var dialog: Dialog?
    
    init(dialog: Dialog) {
        self.dialog = dialog
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let textView: UITextView = {
        let textView = UITextView()
        textView.textContainerInset.left = 5
        textView.textContainerInset.right = 5
        textView.translatesAutoresizingMaskIntoConstraints = false
        return textView
    }()
    
    let placeholderLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        return scrollView
    }()
    
    private var textViewBottomConstraint: NSLayoutConstraint?
    private var textViewHeightConstraint: NSLayoutConstraint?
    
    let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    }()
    
    var messages: [MessageItem] = [
        MessageItem(message: "Короткое сообщение", role: .Receiver),
        MessageItem(message: "Очень длинное сообщение, которое должно корректно отображаться в чате и иметь динамическую высоту. Так же оно должно полность отображаться и не обрезаться.", role: .Sender),
        MessageItem(message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", role: .Receiver),
        MessageItem(message: "The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.", role: .Sender)
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(observeTextChange(_:)), name: UITextView.textDidChangeNotification, object: nil)
        
        collectionView.backgroundColor = .white
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(MessageCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.keyboardDismissMode = UICollectionView.KeyboardDismissMode.interactive
        
        placeholderLabel.text = "Введите ваше сообщение"
        placeholderLabel.textColor = .systemGray4
        placeholderLabel.font = .systemFont(ofSize: 18, weight: .regular)
        
        textView.backgroundColor = .systemGray6
        textView.layer.masksToBounds = true
        textView.layer.cornerRadius = 8
        textView.font = .systemFont(ofSize: 18, weight: .regular)
        textView.isScrollEnabled = false
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(stopEdit))
        view.addGestureRecognizer(tapGesture)
        
        view.backgroundColor = .white
        
        textView.addSubview(placeholderLabel)
        
        scrollView.addSubview(collectionView)
        scrollView.addSubview(textView)
        
        view.addSubview(scrollView)
        
        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.topAnchor),
            scrollView.leftAnchor.constraint(equalTo: view.leftAnchor),
            scrollView.rightAnchor.constraint(equalTo: view.rightAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            
            collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
            collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
            collectionView.rightAnchor.constraint(equalTo: view.rightAnchor),
            collectionView.bottomAnchor.constraint(equalTo: textView.topAnchor, constant: -10),
            
            textView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 25),
            textView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -25),
            textView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -50),
            
            placeholderLabel.leftAnchor.constraint(equalTo: textView.leftAnchor, constant: 10),
            placeholderLabel.rightAnchor.constraint(equalTo: textView.rightAnchor, constant: -10),
            placeholderLabel.topAnchor.constraint(equalTo: textView.topAnchor, constant: 8)
        ])
        
        textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        textViewBottomConstraint?.isActive = true
        
        collectionView.collectionViewLayout.invalidateLayout()
    }
    
    @objc private func keyboardWillShow(_ notification: Notification) {
        guard let userInfo = notification.userInfo,
              let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }

        let keyboardHeight = keyboardFrame.height
        textViewBottomConstraint?.constant = -keyboardHeight + 22
        UIView.animate(withDuration: 0) {
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func keyboardWillHide(_ notification: Notification) {
        textViewBottomConstraint?.constant = 0
        UIView.animate(withDuration: 0) {
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func stopEdit() {
        view.endEditing(true)
    }
    
    @objc private func observeTextChange(_ notification: Notification) {
        if !textView.text.isEmpty {
            placeholderLabel.text = ""
        } else {
            placeholderLabel.text = "Введите ваше сообщение"
        }
        
        let fittingSize = CGSize(width: textView.frame.width, height: CGFloat.greatestFiniteMagnitude)
        let newSize = textView.sizeThatFits(fittingSize)
        
        if newSize.height > 125 {
            textViewHeightConstraint?.constant = 125
            textView.isScrollEnabled = true
        } else {
            textViewHeightConstraint?.constant = newSize.height
            textView.isScrollEnabled = false
        }
    }
    
    @objc private func previewDialogCard() {
        let vc = PreviewViewController()
        vc.modalPresentationStyle = .formSheet
        present(vc, animated: true)
    }
}

extension DialogViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return messages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MessageCell
        if messages[indexPath.item].role == .Receiver {
            cell.isReceiver()
            cell.messageLabel.backgroundColor = .systemGray6
            cell.messageLabel.textColor = .black
        } else {
            cell.isSender()
            cell.messageLabel.backgroundColor = .systemBlue
            cell.messageLabel.textColor = .white
        }
        cell.messageLabel.text = messages[indexPath.row].message
        return cell
    }
}

Ответы (0 шт):