首页 > 解决方案 > 无法调整 uicollectionview 高度

问题描述

我有一个带有一些标题视图的 ViewController 和一个填充所有剩余空间的 UICollectionView。(这是一个聊天应用程序)

我没有使用故事板。我的收藏视图是这样声明的:

self.messagesCollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - barHeight), collectionViewLayout: UICollectionViewFlowLayout())
messagesCollectionView.register(MessageCollectionViewCell.self, forCellWithReuseIdentifier: self.cellReuseIdentifier)
messagesCollectionView.delegate = self
messagesCollectionView.dataSource = self
self.view.addSubview(messagesCollectionView)

然后我有这些函数来正确获取我的数据:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.conversation?.messagesList.count ?? 0
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellReuseIdentifier, for: indexPath) as! MessageCollectionViewCell

    if let message = self.conversation?.messagesList[indexPath.row] {
        cell.createMessage(message: message)
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if let message = self.conversation?.messagesList[indexPath.row] {
        var heightNeeded = message.text.height(withConstrainedWidth: FDDimensions.shared.k_MessageMaxWidth, font: FDFonts.Montserrat_Regular_14 ?? UIFont.systemFont(ofSize: 14))
        heightNeeded += 22
        heightNeeded += 25

        return CGSize(width: self.view.frame.width, height: heightNeeded)
    } else {
        return CGSize(width: 0, height: 0)
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 10
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets.init(top: 10, left: 0, bottom: 10, right: 0)
}

所以这是我得到的一个例子,在调整大小之前有很好的方面:

在此处输入图像描述

我想做的是在键盘出现时调整我的collectionview高度。

这是我的函数中的代码,当键盘出现时触发:

self.messagesCollectionView.frame.size.height -= keyboardSize.height - (FDUtils.shared.getBottomSafeAreaHeight() ?? 0)
self.messagesCollectionView.reloadData()
self.messagesCollectionView.layoutIfNeeded()

这是我得到的结果: 在此处输入图像描述

我所有的细胞都变了,结果完全坏了

知道我哪里错了吗?我试图调整 collectionView 的 contentInsets 但我不能使用它,因为如果我使用该解决方案,滚动条行为将不是逻辑

谢谢

标签: iosswiftuicollectionviewkeyboard

解决方案


键盘抬起时添加监听器

NotificationCenter.default.addObserver(self, selector: #selector(showKeyboard), name: UIResponder.keyboardWillShowNotification, object: nil)

@objc func showKeyboard(notification: Notification) {

        collectionView.scrollToItem(at: IndexPath(row: messagesList.count - 1, section: 0), at: .top, animated: false)
}

谢谢


推荐阅读