简体   繁体   English

当内容大小大于单元格大小时,允许collectionview滚动

[英]allowing collectionview to scroll while the content size is bigger than the cell size

So I have a collectionview inside my vc like so: 所以我在我的vc中有一个collectionview像这样:

lazy var collectionView : UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.headerReferenceSize = CGSize(width: self.view.frame.width, height: 96 + 42.5)
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.delegate = self
    cv.dataSource = self
    cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    cv.alwaysBounceVertical = true
    return cv
}()

it has a header with a total height of 138.5 pixels. 标头的总高度为138.5像素。 so the content size of the collection view where the cells are displayed is view.frame.height - 138.5 . 因此显示单元格的集合视图的内容大小为view.frame.height - 138.5

Inside my collectionview I have cells at a height of 176 pixels each while being view.frame.width wide like so: 在我的collectionview内部,每个单元格的高度为176像素,而view.frame.width宽度如下:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 176)
}

problem is that, when I return a count of 3 cells or less, the collectionview is not scrollable. 问题是,当我返回3个或更少的单元格时,collectionview无法滚动。 If there are 4 cells or more, the header is able to disappear and only the cells inside the collectionview are visible. 如果有4个或更多单元格,则标题可以消失,并且只有collectionview内部的单元格可见。 I want this to happen regardless of there being 1 cell or 4. 我希望无论是否有1个单元格或4个单元格,都会发生这种情况。

If there is only 1 cell inside the collectionview, I want the collectionview to still be scrollable and when the user scrolls downwards, the cell will sit at the top of the screen whilst the header disappears. 如果collectionview内只有1个单元格,则我希望collectionview仍可滚动,并且当用户向下滚动时,该单元格将位于屏幕顶部,而标题消失。

Apologies if it's confusing to understand, it's a little hard to explain. 抱歉,如果难以理解,将很难解释。

You can try collectionView.alwaysBounceVertical = true . 您可以尝试collectionView.alwaysBounceVertical = true

According to the documentation: If this property is set to true and bounces is true, vertical dragging is allowed even if the content is smaller than the bounds of the scroll view . 根据文档:如果将此属性设置为true,并且bounces为true, 则即使内容小于滚动视图的边界,也允许垂直拖动 The default value is false. 默认值为false。

EDIT: 编辑:

If you wish the header element to be scroll away even there is not enough cell to make the collection view contentSize greater then its frame . 如果您希望即使没有足够的单元格也无法滚动标题元素,则使集合视图contentSize大于其frame I think you might consider the following layout: 我认为您可以考虑以下布局:

ScrollView(Height: A, ContentHeight: A+B)
    HeaderView(Height: B)
    CollectionView(Height: A)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM