CollectionView 项目隐藏在顶栏后面

CollectionView items are hidden behind top bar

我有一个消息传递应用程序,问题是第一条消息不可见,当我拖动集合视图以查看最前面的消息时我可以看到它们但是当我松开手指时,集合视图跳回,隐藏屏幕顶部的前 5 条消息

正如我们从图像中看到的那样,有一条消息(实际上顶部有 5 条消息),但是我必须拖动集合视图才能查看这些消息。我认为集合视图的大小实际上比屏幕大,但是 collectionView.frame.heightUIScreen.main.bounds.height 具有相同的高度,可以吗? . 这是我用来设置集合视图的代码:

 /// Function that configures the ChatViewController collection view
    private func configureCollectionView() {
        collectionView?.backgroundColor = Theme.current.chatGeneralBackground
        collectionView?.alwaysBounceVertical = true
        collectionView?.keyboardDismissMode = .onDrag

        // Register the chat cell and the loading cellx`
        collectionView?.register(ChatCell.self, forCellWithReuseIdentifier: chatCellIdentifier)
        collectionView?.register(LoadingCollectionViewCell.self, forCellWithReuseIdentifier: loadingCellIdentifier)

        // Initialize the original height of the collection view
        collectionViewOriginalHeight = collectionView.frame.height
    }

我做错了什么?

从 iOS 7.0 开始,所有视图都会自动置于导航栏、工具栏和标签栏后面,以提供 Apple 所称的 "context"。

例如,如果您不希望视图控制器出现在任何栏杆后面,请在 viewWillAppear

中使用它
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)       
        self.edgesForExtendedLayout = [] 
}

好像是constraints的问题,如果你用的是自定义导航栏top constraints,可以参考一下。如果使用默认导航控制器,您可能需要将顶部约束从安全区域设置为 44。

但是 UIScreen.main.bounds.height 由完整的屏幕组成,包括顶部导航栏和 20 像素的状态栏。对于 collectionView.frame.height,您需要减去这些值。