UICollectionViewFlowLayout not line breaking correctly - ios

I have subclassed flow layout and set it as my collectionViewLayout on my collection view.
Then I set up the layout as follows:
- (id) init
{
if(self = [super init])
{
self.minimumInteritemSpacing = 11.0;
self.scrollDirection = UICollectionViewScrollDirectionVertical;
self.itemSize = CGSizeMake(64.0,32.0);
self.minimumLineSpacing = 10.0;
self.sectionInset = UIEdgeInsetsMake(11.0,95.0,11.0,11.0);
return self;
}
return nil;
}
95 + 64 + 11 + 64 + 11 + 64 + 11 = 320 - i checked it. (thats one left inset, 3 cells, 2 spaces and one right inset)
I have 1 section, 72 items, and my cell for index path function:
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifierForCustomCell forIndexPath:indexPath];
cell.mainLabel.text = [#(indexPath.item) stringValue];
return cell;
}
The output is this:
As you can see, there's just 2 cells per row. Furthermore, it is not displaying every 3rd cell.
I had a look at what flow layout's layout function was producing
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
gives...
This is the first 3 layout attributes in the layoutAttributes [NSArray] and as you can see it has decided to only deem the first 2 and then the 4th item as visible for the rect (320 by 568). This has to be an error in collection view layout, doesn't it? The collection view fills the screen and is 320 wide. So since this is a line breaking layout, no items should be off screen.
With edge insets removed:
It works as it is supposed to. But I would like to have section insets since I need to add some decoration views which need to be in the same scroll view while I need a much bigger lleft inset than right inset.

There is a bug in Apple's UICollectionViewFlowLayout where some cells are displayed out of bounds.
These resources will help you to fix it (you have to create a subclass of UICollectionViewFlowLayout and override this method):
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *newAttributes = [NSMutableArray arrayWithCapacity:attributes.count];
for (UICollectionViewLayoutAttributes *attribute in attributes) {
if ((attribute.representedElementCategory != UICollectionElementCategoryCell) || // always include everything that's not a cell
((attribute.frame.origin.x + attribute.frame.size.width <= (self.collectionViewContentSize.width - self.sectionInset.right)) &&
(attribute.frame.origin.y + attribute.frame.size.height <= (self.collectionViewContentSize.height - self.sectionInset.bottom))))
{
[newAttributes addObject:attribute];
}
}
return newAttributes;
}
Sources for the basis for this fix:
https://gist.github.com/nicksnyder/4075682
UICollectionView flowLayout not wrapping cells correctly (iOS)

Until someone works out whats going on and whether or not this is a bug, the method I am using to fix this currently is:
- (NSArray *)alterAttributes:(NSArray *)attributes
{
for (UICollectionViewLayoutAttributes *attribute in attributes) {
switch (attribute.indexPath.item % 3) {
case 0:
attribute.center = CGPointMake(CellX1,attribute.center.y);
break;
case 1:
attribute.center = CGPointMake(CellX2,attribute.center.y);
break;
case 2:
attribute.center = CGPointMake(CellX3,attribute.center.y);
break;
default:
break;
}
}
return attributes;
}
Manually changing the x coordinates in layoutAttributesForElementsInRect - not really a satisfying solution.

Related

Display CollectionViewCell in starting position

I created a collection view cell with the Xib file. And I have only one cell, but that cell displaying in the center of the collectionView. I want to display cell at starting position of the collectionView.
I fixed contentInset in viewDidLoad and loading cell xib file here,
_listCollectionView.contentInset = UIEdgeInsetsMake(0 , 0, 0, 0);
And my cell size is
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(156,140);
}
Cell displaying like this.
Im not very clear with your question but i think what you are referring to is to align the collectionnView element to the view . You have to use UICollectionViewLayoutAttributes or layoutAttributesforElements to achieve this . Take look at the below code and to make if you want it in Objective c.
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
CGFloat leftMargin = self.sectionInset.left; //initalized to silence compiler, and actaully safer, but not planning to use.
CGFloat maxY = -1.0f;
//this loop assumes attributes are in IndexPath order
for (UICollectionViewLayoutAttributes *attribute in attributes) {
if (attribute.frame.origin.y >= maxY) {
leftMargin = self.sectionInset.left;
}
attribute.frame = CGRectMake(leftMargin, attribute.frame.origin.y,
attribute.frame.size.width, attribute.frame.size.height);
leftMargin += attribute.frame.size.width + self.minimumInteritemSpacing;
maxY = MAX(CGRectGetMaxY(attribute.frame), maxY);
}
return attributes;
}
In collectionView: cellForItemAtIndexPath: function i made changes like this.
Here just i fixed my collectionviewcell x origin position to 0 after loading the cell.
deviceCell= (DeviceCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"DeviceCollectionViewCell" forIndexPath:indexPath];
if (listArray.count == 1) {//Here i fixed the my cell x origin position
CGRect frameRect = deviceCell.frame;//Copy cell frame
frameRect.origin.x = 0;//Set cell origin.x
deviceCell.frame = frameRect;//Reset frame
}

UICollectionViewFlowLayout ignoring section insets for items of different heights - bug or expected?

I'm using UICollectionViewFlowLayout and wanted to apply section insets like below. All my items have the same width but varying heights. The insets work when items within the same section are the same height but not when they are different heights in the same section. Is this expected behaviour for this layout? Do I need to subclass and make a custom one or is something missing?
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
UIEdgeInsets insets = UIEdgeInsetsZero;
CGFloat big = 30;
CGFloat small = 10;
if (section < 5) {
insets = UIEdgeInsetsMake(0, big, 0, small);
} else {
insets = UIEdgeInsetsMake(0, small, 0, big);
}
return insets;
}
For some reason the UICollectionViewFlowLayout has the behaviour to center the cells if you have a single item each row. It ignores the section insets then.
You can solve this issue by overriding the UICollectionViewFlowLayout and change the following two methods:
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *attribute = [super layoutAttributesForItemAtIndexPath:indexPath];
[self fixLayoutAttributeInsets:attribute];
return attribute;
}
And
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *results = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attribute in results)
{
[self fixLayoutAttributeInsets:attribute];
}
return results;
}
The magic:
- (void)fixLayoutAttributeInsets:(UICollectionViewLayoutAttributes *)attribute
{
if ([attribute representedElementKind])
{ //nil means it is a cell, we do not want to change the headers/footers, etc
return;
}
//Get the correct section insets
UIEdgeInsets sectionInsets;
if ([[[self collectionView] delegate] respondsToSelector:#selector(collectionView:layout:insetForSectionAtIndex:)])
{
sectionInsets = [(id<UICollectionViewDelegateFlowLayout>)[[self collectionView] delegate] collectionView:[self collectionView] layout:self insetForSectionAtIndex:[[attribute indexPath] section]];
}
else
{
sectionInsets = [self sectionInset];
}
//Adjust the x position of the view, the size should be correct or else do more stuff here
CGRect frame = [attribute frame];
frame.origin.x = sectionInsets.left;
[attribute setFrame:frame];
}
This solution does not work (and is not needed) if you have multiple cells on a single row so you should check for that case with a boolean or whatever you like... This is just a simple example for this scenario
Doesn't seem to be possible with varying heights, so I made the cells full width and mange the padding logic inside the cell class itself.

How do I create a UICollectionView with column and row headers?

I want to create a UICollectionView that looks like this:
It won't be scrollable or editable. I'm currently wondering how to write the layout for this. I'm guessing it won't be a subclass of UICollectionViewFlowLayout. I can think of a number of ways, but was curious if there was any "right" way. The cells will be animate-able.
Should each row or column be its own section?
I've done something like what you want with a subclass of UICollectionViewFlowLayout. It looks like this,
#implementation MultpleLineLayout {
NSInteger itemWidth;
NSInteger itemHeight;
}
-(id)init {
if (self = [super init]) {
itemWidth = 80;
itemHeight = 80;
}
return self;
}
-(CGSize)collectionViewContentSize {
NSInteger xSize = [self.collectionView numberOfItemsInSection:0] * (itemWidth + 2); // the 2 is for spacing between cells.
NSInteger ySize = [self.collectionView numberOfSections] * (itemHeight + 2);
return CGSizeMake(xSize, ySize);
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path {
UICollectionViewLayoutAttributes* attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:path];
NSInteger xValue;
attributes.size = CGSizeMake(itemWidth,itemHeight);
xValue = itemWidth/2 + path.row * (itemWidth +2);
NSInteger yValue = itemHeight + path.section * (itemHeight +2);
attributes.center = CGPointMake(xValue, yValue);
return attributes;
}
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
NSInteger minRow = (rect.origin.x > 0)? rect.origin.x/(itemWidth +2) : 0; // need to check because bounce gives negative values for x.
NSInteger maxRow = rect.size.width/(itemWidth +2) + minRow;
NSMutableArray* attributes = [NSMutableArray array];
for(NSInteger i=0 ; i < self.collectionView.numberOfSections; i++) {
for (NSInteger j=minRow ; j < maxRow; j++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForItem:j inSection:i];
[attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
}
}
return attributes;
}
The data is arranged as an array of arrays where each inner array supplies the data for one horizontal row. With the values I have in there now, and using your data as an example, the view looked like this,
This is the code I haven the view controller,
#interface ViewController ()
#property (strong,nonatomic) UICollectionView *collectionView;
#property (strong,nonatomic) NSArray *theData;
#end
#implementation ViewController
- (void)viewDidLoad {
self.theData = #[#[#"",#"A",#"B",#"C"],#[#"1",#"115",#"127",#"132"],#[#"2",#"",#"",#"153"],#[#"3",#"",#"199",#""]];
MultpleLineLayout *layout = [[MultpleLineLayout alloc] init];
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.view.backgroundColor = [UIColor blackColor];
[self.view addSubview:self.collectionView];
[self.collectionView registerNib:[UINib nibWithNibName:#"CustomDataCell" bundle:nil] forCellWithReuseIdentifier:#"DataCell"];
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
return [self.theData[section] count];
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return [self.theData count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
DataCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"DataCell" forIndexPath:indexPath];
cell.label.text = self.theData[indexPath.section][indexPath.row];
return cell;
}
You can do it with UICollectionViewFlowLayout but if you go that way you need to count carefully and get the padding (i.e. the top left, and other "empty" cells) right. If you miscount it's obvious because the flow ruins everything quickly and you will find your header cells halfway down your columns. (I have done a similar thing)
I only did it that way because of a fear of custom layouts - but in fact it is as easy as UITableView. If your layout does not scroll at all then yours will be particularly simple as your only real work will be calculating frame values for cells, to be returned in layoutAttributesForItemAtIndexPath. Since your whole view fits in the visible area, layoutAttributesForElementsInRect will mean you simply iterate through all the cells in the view. collectionViewContentSize will be the size of your view.
Looking at your sample picture you might find it convenient to organise your data as a dictionary of arrays, one per column. You can get a column array by name ("A", "B" etc.) and the position in the array corresponds to the value in the leftmost column, which you might name "index".
There are many more methods you can use but those are the basics, and will get your basic display up and running.

Subclassing UICollectionView, skipping indexes

I was trying to subclass collection view layout , in order to get a constant spacing between vertical cells. i have 2 columns and many rows, with dynamic cells height .
The goal is Pinterest like grid.
So i have subclassed the layout class, and now has a constant space between cells, but there is a serious problem caused by that .
When i scroll down, the left cells are not being loaded in time= there are many "holes" so that there is blank space of 3-4 cells, and than- they suddenly appears at once -lately.
so i have this :
1 2
3 4
6
8
than 5 and 7 appears when i scroll down more . i just can't get rid of this !
EDIT: seems that when all cells are in the same size, this will not happens ,so when i return here a constant height :
//cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
{
CGSize size=CGSizeMake( imageWidth, scale*height+[Globals sharedGlobals].gridViewStripHeight );
return size;
My subclass(which when not using it, also solves the problem )
//the subclass
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray* arr = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes* atts in arr)
{
if (nil == atts.representedElementKind)
{
NSIndexPath* ip = atts.indexPath;
atts.frame = [self layoutAttributesForItemAtIndexPath:ip].frame;
}
}
return arr;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes* atts =[super layoutAttributesForItemAtIndexPath:indexPath];
if (indexPath.item == 0 || indexPath.item == 1) // degenerate case 1, first item of section
return atts;
NSIndexPath* ipPrev =
[NSIndexPath indexPathForItem:indexPath.item-2 inSection:indexPath.section];
CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame;
CGFloat rightPrev = fPrev.origin.y + fPrev.size.height + 50;
if (atts.frame.origin.y <= rightPrev) // degenerate case 2, first item of line
return atts;
CGRect f = atts.frame;
f.origin.y = rightPrev;
atts.frame = f;
return atts;
}
To use it i have :
UICollectionViewFlowLayout *layout=[[TopAlignedCollectionViewFlowLayout alloc] init]; subclass
CGRect size=CGRectMake( ([UIScreen mainScreen].bounds.size.width-collectionWidth)/2,
upperLineMargin, collectionWidth, [UIScreen mainScreen].bounds.size.height-upperLineMargin);
self.GridView=[[UICollectionView alloc] initWithFrame:size collectionViewLayout:layout];
[self.GridView registerClass:[GridCell class] forCellWithReuseIdentifier:#"Cell"];

iOS UICollectionView header & footer location

Working in iOS 7, how does one specify where the header & footer boxes go in a UICollectionView?
I have a custom UICollectionViewFlowLayout. I have overwritten
-(void)prepareLayout
-(NSArray*) layoutAttributesForElementsInRect:(CGRect)rect
-(UICollectionViewLayoutAttributes*) layoutAttributesForSupplementaryViewOfKind: (NSString*)kind atIndexPath:(NSIndexPath*)indexPath
My problem is, I'm not sure how to specify header location. I have already specified that a header exists in prepareLayout:
-(void)prepareLayout
{
[super prepareLayout];
boundsSize = self.collectionView.bounds.size;
midX = boundsSize.width / 2.0f;
curIndex = 0;
self.headerReferenceSize = CGSizeMake(CELL_SIZE, TITLE_HEIGHT);
self.footerReferenceSize = CGSizeMake(0, 0);
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.sectionInset = UIEdgeInsetsMake(TOP_INSET, LEFT_INSET, BOTTOM_INSET, RIGHT_INSET);
self.minimumLineSpacing = LINE_SPACING;
self.minimumInteritemSpacing = INTERIM_SPACING;
self.itemSize = CGSizeMake(CELL_SIZE, CELL_SIZE);
}
I just don't know the right property of my custom FlowLayout to set, as there doesn't seem to be something like "HeaderLocation" to set, either as a LayoutAttributes or in the layout object itself. Right now, it is appearing to the side/between my images, when I'd like them to be appearing above each image (horizontal scroll).
I have tried the following:
-(UICollectionReusableView*) collectionView: (UICollectionView*)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath
{
NSLog(#"**ViewForSupplementaryElementOfKind called***");
CGFloat centerX = collectionView.center.x;
CGFloat centerY = collectionView.center.y;
CGFloat titleWidth = [MyLayout titleWidth];
CGFloat titleHeight = [MyLayout titleHeight];
MyTitleView* titleView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:ImageTitleIdentifier forIndexPath:indexPath];
titleView.frame = CGRectMake(centerX - titleWidth/2.0,
0.0,
titleWidth,
titleHeight);
return titleView;
}
This doesn't work. The title appears above overlapped with a bunch of other titles, then the moment I start scrolling (horizontally), they jump back into the wrong place, horizontally between the images rather than above.
PS> Please do not suggest anything that has to do with NIB or XIB placement. I am using a UICollectionView, NOT a UICollectionViewController, so I actually have no prototypical cell to work with. The layout is being done entirely programatically -- from code alone -- so I can't simply open a XIB file and adjust the location of a text box.
Amending the attributes returned by -layoutAttributesForElementsInRect is the right approach, but if you want to alter the position of offscreen headers and footers, you may need to fetch the supplementary view attributes yourself.
For example, in your UICollectionViewFlowLayout subclass:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *attributesArray = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
// the call to super only returns attributes for headers that are in the bounds,
// so locate attributes for out of bounds headers and include them in the array
NSMutableIndexSet *omittedSections = [NSMutableIndexSet indexSet];
for (UICollectionViewLayoutAttributes *attributes in attributesArray) {
if (attributes.representedElementCategory == UICollectionElementCategoryCell) {
[omittedSections addIndex:attributes.indexPath.section];
}
}
for (UICollectionViewLayoutAttributes *attributes in attributesArray) {
if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {
[omittedSections removeIndex:attributes.indexPath.section];
}
}
[omittedSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:idx];
UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
atIndexPath:indexPath];
[attributesArray addObject:attributes];
}];
for (UICollectionViewLayoutAttributes *attributes in attributesArray) {
if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {
// adjust any aspect of each header's attributes here, including frame or zIndex
}
}
return attributesArray;
}
CollectionView Header height is set below Collectionview delegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
And Set view in Collectionview Header in Below Delegate
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView * view = nil;
if ([kind isEqualToString:UICollectionElementKindSectionHeader])
{
ColorSectionHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withReuseIdentifier:NSStringFromClass([ColorSectionHeaderView class])
forIndexPath:indexPath];
header.sectionIndex = indexPath.section;
header.hideDelete = collectionView.numberOfSections == 1; // hide when only one section
header.delegate = self;
view = header;
}
return view;
}
Ragistred Class in ViewDidLoad
-(void)ViewDidLoad
{
[collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ColorSectionFooterView class]) bundle:nil]
forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
withReuseIdentifier:NSStringFromClass([ColorSectionFooterView class])];
[Super ViewDidLoad];
}

Resources