首页 > 解决方案 > 当 CV contentInset 更新时(带视频),尽管 .isHidden = true,仍会显示 collectionViewCell 子视图

问题描述

我正在制作像 iMessage 这样的聊天应用程序。我使用UICollectionView带有垂直的 aFlowLayout每个单元格是一个堆栈视图,其中包含 (1) 一个“标题”视图(包含日期 UILabel,如 iMessage 中),以及 (2) 在其下方,我将消息放入的气泡 UILabel文本。

这是我用来使单元格出列的代码:

let pos = indexPath.row
let message:Message = messagesData[pos]

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MessageCollectionViewCell

cell.setMessage(message)
cell.headerView.isHidden = pos == 0 || message.dateDMY != messages[pos - 1].dateDMY

return cell

就像在 iMessage 中一样,如果上一条消息的日期不同或者它是第一条消息(用户滚动到顶部),我会显示它。

我使用.interactive键盘,底部栏作为inputAccessoryView. 为了始终在底栏上方显示最后一条消息,我为通知实现了此侦听器UIResponder.keyboardWillChangeFrameNotification

@objc func onKeyboardChangeFrame(notif:Notification)
{
    
    let userInfo = notif.userInfo!
    let beginFrameValue = userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! CGRect
    let endFrameValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
    
    if(!beginFrameValue.equalTo(endFrameValue))
    {   
        let oldContentInset = collectionView.contentInset.bottom
        
        UIView.animate(withDuration:0.05)
        {
            // endFrameValue.height contains the height of the keyboard + inputAccessoryView height, so it's the perfect value for the contentInset
            self.collectionView.contentInset.bottom = endFrameValue.height
            self.collectionView.scrollIndicatorInsets.bottom = endFrameValue.height
        }
       
        // no need to scroll when inset is reduced : the cells automatically go down. But when the inset is increased, additional scroll is needed
        if(endFrameValue.height > oldContentInset)
        {
            DispatchQueue.main.async {
                self.collectionView.scrollToBottomCell()
            }
        }
    }

}

当用户发送大约 15 条消息时(因此插入的所有消息单元格都无法进入屏幕),然后快速关闭键盘,将 CV contentInset 调整为减小(显示最后一条消息靠近底栏)。由于 contentInset 减少,新的单元格被插入到 CV 的顶部,因为有可用空间。

尽管 cellForItem 函数明确告知isHidden = true. 使用调试器,我可以看到这些标头确实将其 isHidden 设置为 true,但无论如何都会显示它们。此外,布局检查器中未检测到这些标题。.

有人知道出了什么问题吗?

标签: swiftuicollectionviewthread-safety

解决方案


推荐阅读