Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

ios - uicollectionview remove top padding

I have a UICollectionView that is the entire view but it lives inside "view" (it is not UICollectionViewController). Adding a cell to this collection view shows it in the following order in storyboard:

Storyboard View

This is how it looks in the emulator:

Emulator View

I don't understand how to get rid of that view. All the insets are at zero in Storyboard Size Inspector for collection view. Just to be sure, I also have the following code:

override func viewWillLayoutSubviews() {
    let layout = self.collectionViewProducts.collectionViewLayout as! UICollectionViewFlowLayout

    let containerWidth = UIScreen.main.bounds.size.width - 40.0
    let itemWidth = (containerWidth / 3.0)
    let itemHeight = (itemWidth / 0.75) + 30

    layout.sectionInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)

    layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
}

How can I get rid of that top padding?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can fix top padding issue by considering one of the following method.

Method 1: Natural way to fix your problem by setting up your collectionView dimensions properly from StoryBoard.

enter image description here

Method 2: **Updated**

You can validate collection frame in viewDidLayoutSubviews or viewWillLayoutSubviews

  override func viewDidLayoutSubviews() {
     collectionView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
}

Method 3: You can Adjust Scroll View Insets from your StoryBoard Attributes Inspector.

enter image description here

Method 4: You can fix this issue programatically by adjusting CollectionView contentInset.

collectionView.contentInset = UIEdgeInsets(top: **Any Value**, left: 0, bottom: 0, right: 0)

Output with top padding 5:

enter image description here

Output with top padding 44:

enter image description here

Output with top padding 64:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...