简体   繁体   中英

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

So I have a collectionview inside my vc like so:

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. so the content size of the collection view where the cells are displayed is 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:

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. If there are 4 cells or more, the header is able to disappear and only the cells inside the collectionview are visible. I want this to happen regardless of there being 1 cell or 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.

Apologies if it's confusing to understand, it's a little hard to explain.

You can try 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 . The default value is 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 . I think you might consider the following layout:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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