How to remove the gap between header and cell of UICollectionView? - ios

I have a UICollectionView and it has a header and a cell.
I want to remove the gap between the header and the cell..
How to do that in swift?
Here is my view...
I added background colour to the collectionView and header and cell also..
Please see the screenshot.

Use the property section Inset of UICollectionViewFlowLayout
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10)
// Here you can set according your requirement
For more reference: http://www.brianjcoleman.com/tutorial-collection-view-using-swift/

use the property sectionInset of UICollectionViewFlowLayout:
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 1;
in Swift:
var layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 1

Attaching screenshot of storyboard screen. Set as per that your storyboard and check. Hope your problem will be solved.

I Forgot to set section Inset to zero.
It solved my problem.
Thanks everyone.

try this:
override func viewWillAppear(animated: Bool) {
self.automaticallyAdjustsScrollViewInsets = false;
}
On UICollectionViewDelegate:
let k_cViewPadding = 8.0
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellDiffference:CGFloat = CGFloat(k_cViewPadding*4)
return(CGSizeMake((collectionView.frame.size.width-cellDiffference)/3, (collectionView.frame.size.width-cellDiffference)/3))
}

Here is my sample code you have to set UIEdgeInsets for spacing.
private let collectionViewLayout: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionView.ScrollDirection.horizontal
layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView.register(TopExpertCustomCell.self, forCellWithReuseIdentifier: "TopExpertCollectionViewCell")
collectionView.backgroundColor = UIColor(hex: "#F1F1F1")
return collectionView
}()

Custom your UIEdgeInsetsMake:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0,0,0,0); //{top, left, bottom, right};
}

Related

UICollectionView sectionInsets not respected when using Header Cells

I am trying to create a collection view that has a header cell (dynamically sized) and some "normal" content cells (also dynamically sized). Therefore, the collection view is initialized as follows:
private lazy var timelineCollectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.sectionInset = UIEdgeInsets(top: self.coloredTitleBarHeight, left: 0, bottom: 0, right: 0) // assume that coloredTitlebarHeight is a constant of 120
flowLayout.estimatedItemSize = CGSize(width: self.view.frame.width, height: 10)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
cv.alwaysBounceVertical = true
cv.contentInsetAdjustmentBehavior = .never
cv.backgroundColor = .clear
cv.scrollIndicatorInsets = UIEdgeInsets(top: self.coloredTitleBarHeight - self.getStatusBarHeight(), left: 0, bottom: 0, right: 0)
cv.delegate = self
cv.dataSource = self
cv.register(TLContentCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "content-header-cell")
cv.register(TLContentCell.self, forCellWithReuseIdentifier: "comment-cell")
return cv
}()
The collectionView is part of a ViewController that conforms to the following protocols: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
Then, I use the following code to create a header cell:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "content-header-cell", for: indexPath) as! TLContentCell
cell.timelineContent = tlContentItem
cell.delegate = self
return cell
}
Last but not least, the dequeuing of the regular cells:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "comment-cell", for: indexPath)
return cell
}
Output:
The collectionView displays the header cell as well as the item cells, however, the section Insets are not applied.
I would be very happy if you could provide me with any suggestion regarding this strange behavior.
Section insets are applied to contents only in UICollectionViewFlowLayout.
Using Section Insets to Tweak the Margins of Your Content
Section insets are a way to adjust the space available for laying out cells.
You can use insets to insert space after a section’s header view and
before its footer view. You can also use insets to insert space around
the sides of the content. Figure 3-5 demonstrates how insets affect
some content in a vertically scrolling flow layout. source

Swift iOS how to remove top padding UICollectionView

override func viewDidLoad(){
super.viewDidLoad()
scrollView.collectionViewLayout = layout
scrollView.delegate = self
scrollView.dataSource = self
scrollView.contentInset = .zero
scrollView.scrollIndicatorInsets = .zero
scrollView.isDirectionalLockEnabled = true
scrollView.register(UINib(nibName: "RadioView", bundle: nil), forCellWithReuseIdentifier: "RadioViewController")
}
lazy var layout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.headerReferenceSize = .zero
layout.sectionInset = .zero
layout.scrollDirection = UICollectionViewScrollDirection.horizontal
return layout
}()
background Color Red is UICollectionView
backgorund Color Black is UICollectionViewCell
i want move Cell to left top
If it's not a Layout constraint problem, than:
collectionView.contentInset = UIEdgeInsets.zero
It is also possible that you have implemented:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//...
}
In that case you need to set the methods return value top property to 0
Try setting these two property of UIViewController in viewDidLoad
extendedLayoutIncludesOpaqueBars = true
automaticallyAdjustsScrollViewInsets = false
Please check the header size in the storyboard, try setting them to zero.
I think this is the problem set the value of Y component to zero

lazy loading a uicollectionview cause app crash when collectionview dequeues a reusable cell

my HomeHorizontalSpecialCell inherited UICollectionViewCell, and has a property which is collectionView. And this collectionView constructs by lazy loading
private lazy var _collectionView: UICollectionView! = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 10
let itemWidth = (kScreenWidth - 4 * layout.minimumLineSpacing) / 3.4
let itemHeight = itemWidth
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: itemHeight), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.white
collectionView.contentInset = UIEdgeInsetsMake(0, 7, 0, 7)
// register cell
collectionView.register(HomeHorizontalSpecialGoodCell.self, forCellWithReuseIdentifier: HomeHorizontalSpecialCell.reuseSpecialCellID)
collectionView.showsHorizontalScrollIndicator = false
self.contentView.addSubview(collectionView)
return collectionView
}()
when set data, this collectionView calls to reloadData method and begin to construct and register cell.
in dataSource methods, I dequeue these registered reusable cells
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// crash at here on big size iPhone
let specialGoodCell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeHorizontalSpecialCell.reuseSpecialCellID, for: indexPath) as! HomeHorizontalSpecialGoodCell
if indexPath.row != (_dataList?._item.count)! { // good cells
specialGoodCell.goodModel = _dataList?._item[indexPath.row]
} else { // last cell
specialGoodCell.setMoreImage("spe_more")
}
return specialGoodCell
}
force to unwrap a cell cause App crash when collectionView dequeue a cell on some big size iPhones, but small size not.
i found the situation where directly initial HomeHorizontalSpecialCell at first time at big size iPhone, but at small size it need to scroll collectionView to initial this cell instance.
why does app crash when loading this cell at big size iPhone?
someone can help?
A good way to do this is using the viewController as the datasource and delegate of the collectionView. Maybe this article can help you.
Putting a UICollectionView in a UITableViewCell in Swift

How to achieve different number of columns for different rows in collection view [duplicate]

This question already has answers here:
UICollectionView Layout like SnapChat?
(2 answers)
Closed 5 years ago.
How can I achieve the layout shown in the image using the collection view?
I am trying to achieve it by using the waterfall flow layout from the below link but not getting success.
https://github.com/chiahsien/CHTCollectionViewWaterfallLayout
Below is the code by which I am trying to do so.
override func viewDidLoad() {
super.viewDidLoad()
let identifier = String(describing: collectionCell.self)
collectionView.register("collectionCell", forCellWithReuseIdentifier: "collectionCell")
collectionView.register(UINib(nibName: "collectionCell", bundle: nil), forCellWithReuseIdentifier: identifier)
let layout = CHTCollectionViewWaterfallLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.minimumInteritemSpacing = 0
layout.minimumColumnSpacing = 10
collectionView.collectionViewLayout = layout
}
//For setting the size of the cell
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let width = Double((self.collectionView.bounds.size.width-(4*minimumSpaceBetweenCells))/3)
if indexPath.row == 0 {
return CGSize(width:width * 2, height: width * 2)
}
else
{
return CGSize(width:width, height: width)
}
}
But it is just displaying the 2 columns with same size for all the rows.
Please let me know if anyone has idea how to do it.
Thanks in advance.
I would suggest to create a new tableView inside each collectionViewCell and set tableView's numberOfRows for the number of columns you want.

UICollectionView container padding

I am trying to add padding to the container of a UICollectionView. I would like it to appear as such that there is a 10pt padding all around. So in the example screen, there is a 10pt padding on the bottom from:
layout.minimumInteritemSpacing = layout.minimumLineSpacing = 10;
I am using a UICollectionViewFlowLayout to layout the cells. I have also tried a "trick" where I add a 10pt view on top, but the content doesn't appear to scroll through the view since they are separate.
Please try to put following code inside viewDidLoad():
collectionView!.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
This will add padding to every side of the collectionView.
PS: I know the question is here for a while but it might help somebody ;)
It seems like the sectionInset property of your UICollectionViewFlowLayout is what you need to modify.
You can use a UIEdgeInsetsMake to create a UIEdgeInsets with margins for top, left, right, and bottom, and set this to the sectionInset property.
Here's the documentation for UICollectionViewFlowLayout: https://developer.apple.com/library/ios/documentation/uikit/reference/UICollectionViewFlowLayout_class/Reference/Reference.html
I used a couple of methods from the UICollectionViewDelegateFlowLayout delegate to accomplish what I was looking for. I was attempting to add 'padding' to cells that had a shadow. This was to ensure they had the effect of 'floating,' and were not touching the edges of the UICollectionView.
First, call the sizeForItemAt indexPath method and give the cells a size:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width * 0.80, height: collectionView.bounds.height * 0.98)
}
Then, call the insetForSectionAt section method, and set the insets for the cells:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 20, left: 25, bottom: 20, right: 25)
}
If you're using configurations, set the contentInsetsReference on the layout's configuration to follow layoutMargins, then set layoutMargins on the collectionView itself.
var config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
config.headerMode = .supplementary
let layout = UICollectionViewCompositionalLayout.list(using: config)
layout.configuration.contentInsetsReference = .layoutMargins
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.layoutMargins = .init(top: 16, left: 64, bottom: 16, right: 64)
In case you're using a UICollectionLayoutListConfiguration, it seems that to get smaller margins with certain appearances, you've to do that on section level like this:
private func createLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout() { (sectionIndex, layoutEnvironment) -> NSCollectionLayoutSection? in
// Create a list configuration as usual
var config = UICollectionLayoutListConfiguration(appearance: .sidebarPlain)
config.headerMode = .supplementary
// Change the section's contentInsets to adjust the side margins
let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: layoutEnvironment)
section.contentInsets.leading = 10
section.contentInsets.trailing = 10
return section
}
return layout
}
Based on feedback from Apple (https://developer.apple.com/forums/thread/679863)

Resources