UICollectionView's cellForItemAtIndexPath is not being called - ios

Only my second time using UICollectionView's and perhaps I have bitten off more than I can chew but nevertheless:
I am implementing a UICollectionView (myCollectionView) that uses custom UICollectionViewCell's that I have subclassed. The subclassed cells (FullReceiptCell) contain UITableView's and are the size of the viewcontroller. I am trying to allow for horizontal scrolling between the FullReceiptCells.
The subclassed UICollectionViewController that contains myCollectionView is being pushed on to a nav controller stack. Currently, myCollectionView loas and horizontal scrolling is enabled. However, no cells are visible. I have confirmed that
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
has run and is returning an integer greater than 0. I have also confirmed that myCollectionView's delegate and datasource are properly set in IB to the subclassed UICollectionViewController.
The method where the cells are to be loaded:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
is not being called.
Here is where I push the UICollectionViewController and my viewDidLoad method within that controller (NOTE: initWithBill is an override of the normal initializer):
In the prior ViewControllers .m file:
FullReceiptViewController *test = [[FullReceiptViewController alloc] initWithBill:currentBill];
test.title = #"Review";
[self.navigationController pushViewController:test animated:YES];
In FullReceiptViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self.myCollectionView registerClass:[FullReceiptCell class] forCellWithReuseIdentifier:#"FullReceiptCellIdentifier"];
self.myCollectionView.pagingEnabled = YES;
// Setup flowlayout
self.myCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[self.myCollectionViewFlowLayout setItemSize:CGSizeMake(320, 548)];
[self.myCollectionViewFlowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
[self.myCollectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
self.myCollectionViewFlowLayout.minimumLineSpacing = 0;
self.myCollectionViewFlowLayout.minimumInteritemSpacing = 0;
[self.myCollectionView setCollectionViewLayout:myCollectionViewFlowLayout];
//testing to see if the collection view is loading
self.myCollectionView.backgroundColor = [UIColor colorWithWhite:0.25f alpha:1.0f];
Any clue as to why it is not being called?

For those who stumble here later.... the reason:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
was not being called was because of the itemSize for the collectionViewFlowLayout's height was too big.
[self.myCollectionViewFlowLayout setItemSize:CGSizeMake(320, 548)];
If I change the height to 410, it will execute cellForItemAtIndexPath.

In my case, it was because my layout class incorrectly subclassed from UICollectionViewLayout instead of UICollectionViewFlowLayout

The cellForItemAtIndexPath will not get called if you do not provide the content size information to collection view.
If you are using Flow layout: You need to set the item sizes properly.
If you have a custom layout subclassed from UICollectionViewLayout: Ensure you are returning a proper size from the collectionViewContentSize method.
In case of the latter, you will also observe that your layoutAttributesForElementsRect is also not called. The reason is that you have not specified what is your content size and by default the size will be CGSizeZero. This basically tell collection view that you don't have any content to paint so it does not bother asking you for attributes or cells.
So, just override collectionViewContentSize and provide a proper size there, it should solve your problem.

For a more complicated view hierachy please check this blog. It saved my life!
self.automaticallyAdjustsScrollViewInsets = NO;

Maybe I'm just overlooking it, but it appears your missing your delegate and data source. In your header file, make sure you have added these:
<UICollectionViewDelegate, UICollectionViewDataSource>
and in your viewDidLoad method add this:
self.myCollectionView.delegate = self;
self.myCollectionView.dataSource = self;
Also, if you are loading it via an .xib, make sure you are have connected the IBOutlet to the UICollectionView.

If your class is subclass from UICollectionviewController and you are creating collectionView programmatically then use
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Vertical
layout.itemSize = CGSizeMake(50, 50)
collectionView?.setCollectionViewLayout(layout, animated: false)

I was using autolayout, and in my case height constraint was missing

In my case, what I had very stupidly forgotten to do was implement the UICollectionViewDataSource protocol method numberOfItemsInSection, so that is another thing to check.

My issue was that I had 2 collection views within the same view, and both were sharing a computed UICollectionViewFlowLayout instance. Once I created separate instances of the same flow layout, it worked fine.

I was having a similar problem. But instead cellForItemAtIndexPath was called when the number of items was > 1, but not when there was only a single item. I tried many of the proposed solutions here and similar to many I found that it had to do with item sizing. For me the solution was to change the estimate size of the UICollectionView from Automatic to Custom.

In my case I had the collectionView in a UIStackView with alignment = .center. So the collectionView did not have a width. When setting the stackView.alignment to .fill everything was fine.

Ten minutes ago I also encountered this problem, I made a silly mistake.
My intention is to use UICollectionViewFlowLayout,
But because of mistakes, I used UICollectionViewLayout.

I forgot to set the autoresizing mask to false on the collection view:
collectionView.translatesAutoresizingMaskIntoConstraints = false

Also, make sure that reloadData is not called while collection view is updating with animation (insert, delete, update or performBatchUpdates).

In my case, set collectionView.prefetchingEnabled = NO; solved my problem.
Only works on iOS 10.

It was happening for me when item height == 0 by fixing that cellForItem method was called.

In my case, changing UINavigationBar's translucent to NO solved the problem.

In Xcode 7.0.1, we got this problem when we copied a storyboard and accompanying code from another project. The collection view had a custom flow layout set in the storyboard. Solution was to:
Remove the flow layout in IB
Compile/run the app
Set the flow layout back
Now it worked :)

In storyboard/xib UICollectionView property cellSize MUST not be {0, 0}

If you're using collection view protocols you must connect the CollectionViewDataSource and CollectionViewDelegate protocols to your ViewController.

Make sure numberOfSectionsInCollectionView returns a positive integer as well.
There has to be at least one section in the collection.

Make sure -(NSInteger) collectionView:numberOfItemsInSection: is returning a positive (read, greater than zero) value. It may be a matter of placing [self.collectionView reloadData]; in the completion handler.

For me, I update the height of self.view (the collectionView's superview) via autolayout, and MUST call layoutIfNeeded after that.
[self.view mas_updateConstraints:^(MASConstraintMaker *make) {
make.height.equalTo(#(height));
}];
[self.view layoutIfNeeded];

When using UICollectionViewDelegateFlowLayout be careful on what this function returns. Both width and height should be greater than 0. I used window as frame reference but due to complicated view hierarchy window was nil at runtime. If you need adjust the width of the element based on screen width use UIScreen.main.bounds.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {}

It can be realated layout problems. Check layout warnings from console, if exist.

In my case the collection view was not fully visible in its parent view due to wrong auto layout constraints. So fixing the constraints made the collection view all visible and cellForItemAtIndexPath was called.

Same happened to me. I had 2 UICollectionViews and I removed once since I didn't need that. After that I realised that the CellForItemAtIndexPath was not getting called but the other required methods. I tried all of the above but then I did the standard magic. Removed the collection view from storyboard and added again. Then it started working. Not sure why and I have no explanation but maybe some connection issues.

Just resolved this issue, for a somewhat specific situation.
In my case, I was manually initializing the UICollectionViewController in a parent ViewController, and then adding the UICollectionViewController's view as a subview.
I resolved the issue by calling 'setNeedsLayout' and/or 'setNeedsDisplay' on the collectionView in the parent's viewDidAppear:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[_collection.view setNeedsLayout];
[_collection.view setNeedsDisplay];
}

reloadSections instead of reloadData did it for me.
I don't know why reloadData did not work.

In my case I had to adjust the estimated Content size. content size did not do it.
let layout = collectionVC.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: 100, height: 100)
layout.estimatedItemSize = CGSize(width: 100, height: 100)

Related

UITableViewCell subviews report incorrect width when using size classes

For some reason, when using size classes in xcode 6, I am getting incorrect widths for subviews in my cell. I have a UIImageView with autolayout for sizing (constant: 10 for top, L/R, bottom).
When calling the following from tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!):
println("w: \(cell.mapSnapshotImageView.bounds.size.width) h: \(cell.mapSnapshotImageView.bounds.size.height)")
I always get:
w: 580.0 h: 80.0
Even though it should be w: 300.0 h: 80.0 based on my 320x100 cell on an iPhone 5S.
Everything displays correctly, but I want to use the width of the subview for some calculations for other subviews. Any ideas as to why this is happening? Bug report or working as designed?
EDIT:
This issue only applies to cells that are loaded initially. When cells are reused, the issue does not present itself. println output on reused cells:
w: 300.0 h: 80.0
Call cell.layoutIfNeeded() in willDisplayCell:forRowAtIndexPath before accessing the frames. That will do the trick.
I also ran into this issue. When you dynamically change the size of the views the subviews need to update their values accordingly. You are referencing the values before they have been updated.
My work around was to reference the values after they had been updated. In this case it was in viewDidAppear(). Hope this provides some use. I spent a while trying to figure it out.
in my case I was getting the bounds of a view in the layoutSubviews method but I forgot to call [super layoutSubviews]. So, my code looks like blow
- (void)layoutSubviews {
[super layoutSubviews]; // this line to add
self.layerToAdd.frame = self.viewContainer.bounds;
}
You can try in the method layoutSubviews(), after calling [cell layoutIfNeeded] to get "right" values for the subviews.

UICollectionView working on iOS7 but not on iOS6

My UICollectionView cells don't get displayed on iOS6, because my delegate method cellForItemAtIndexPath doesn't get called. I suspect because of this warning:
the behavior of the UICollectionViewFlowLayout is not defined because:
the item height must be less that the height of the `UICollectionView`
minus the section inset's top and bottom values.
I don't get the warning on iOS7, and all the cells display correctly there too.
I've set my collectionView frame to height 270 in the .xib and there are no insets defined.
I've set my cell height to 270 in the .xib.
I can print out my collectionView frame at runtime and it's 271.
Also, my collectionview is actually inside a custom tableview cell.
Any ideas?
Thanks!
Try to set self.automaticallyAdjustsScrollViewInsets = NO
This was introduced in ios7 so you might want to wrap that with an ios version check, if you are supporting ios6 and below.
This fixed my problem! In my .xib, setting my Collection View Size Cell Size to a smaller value.
My setup is that I have this collectionview inside a custom tableview cell and
I do return the height of my tableview cell programatically (depending on the content). So it could be that my warnings had to do with my collectionview not fitting inside the tableview cell. So setting the initial collectionview to a smaller value fixed it.
I was on the wrong path thinking that the problem was with my collectionview and its colletionview cell.
Maybe?
self.automaticallyAdjustsScrollViewInsets = NO
actually did the trick. it also resolved my issue in swift, where the cells of a horizontal flow layout had a frame top of -32 (???) and did not fit into the collection view properly.
I found that I had to manually set self.collectionView.collectionViewLayout.itemSize in viewWillLayoutSubviews.
- (void)viewWillLayoutSubviews {
self.collectionView.collectionViewLayout.itemSize = CGRectMake(...);
}
Another possibility to generate the same trick would be to implement the method
collectionView:layout:sizeForItemAtIndexPath:
I have the same issue, in my case the size of collectionCell in storyboard is 96x96 and also under -(CGSize)collectionView:layout:sizeForItemAtIndexPath:
the solution was removing this delegate:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
UIEdgeInsets insets = {.left = 10, .right = 10, .top = 5, .bottom = 5};
return insets;
}
And by the way this is under ios7, it's late but hope this will help some.. Cheers..
Set:
self.itemSize = CGSizeMake(1, 1);

Change scroll direction in UICollectionView

I have a UICollectionView which I have setup, everything works fine (selection, headers, etc), however, I want to change the scroll direction in some situations.
In short if I go into the story board and change the scrollDirection it works fine but I want to do it programatically!
I have tried to change the scroll direction of the collection view directly with something like
[myCollectionView setScrollDirection:....and so on.......
But this does not work, I can not find scrollDirection or similar in there.
I have also tried to setup a flow layout but I am sure i am doing this wrong (i.e. trying to set a ViewLayout to a FlowLayout).
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[myCollectionView setCollectionViewLayout:flowLayout];
This crashes with a lot of Constraint problems and I suspect I need to do a lot more work with the flowLayout (from what I have found it is a bit above me right now).
It should also be noted that I am using a custom cell, headers and footers.
In short is there an easy way to do this or not? OR does anyone know a good Flow Layout tutorial?
EDIT
I setup the collection view as such;
[myCollectionView setDataSource:self];
[myCollectionView setDelegate:self];
I implement these delegate methods and all work fine
viewForSupplementaryElementOfKind
numberOfSectionsInCollectionView
numberOfItemsInSection
cellForItemAtIndexPath
didSelectItemAtIndexPath
I have added the DataSource and Delegate to the .h and also the FlowLayout delegate BUT I am not sure what I should also have for the latter.
Most of the visual layout is done in Story Board, there are a few things such as Font, size and colour which I do programatically.
ANOTHER EDIT
This is the error when I try to change the FlowLayout, I also get this when I try and invalidate the layout.
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
"<NSAutoresizingMaskLayoutConstraint:0x89967f0 h=--& v=--& V:[menuCell:0x8991700(50)]>",
"<NSLayoutConstraint:0x8991200 menuCell:0x8991700.bottom == UILabel:0x8992be0.bottom + 100>",
"<NSLayoutConstraint:0x898fd50 UILabel:0x8992be0.top == menuCell:0x8991700.top + 3>"
Will attempt to recover by breaking constraint
Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.
do this:
- (IBAction)changeDirection:(UIButton *)sender
{
UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)[self.collectionView collectionViewLayout];
if(layout.scrollDirection == UICollectionViewScrollDirectionHorizontal)
{
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
}
else
{
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}
}
It works for me.
In swift you can do this:
//From the collection view subclass
if let layout: UICollectionViewFlowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .Vertical
}
Ok, try calling invalidateLayout on your collection view like so:
[myCollectionView.collectionViewLayout invalidateLayout];
This forces the collection view to update its layout at that point (See apple documentation here). I'm not certain, but I don't imagine this is called when you change the scroll direction.
See if that gets you anywhere near!
You can do it with property observer didSet{} with your collection view outlet.
Assuming that the outlet for the collectionView is myCollectionView, in the code add a didSet property observer to the outlet and change the layout's direction. Something like-
#IBOutlet weak var myCollectionView:UICollectionView!{
didSet{
let layout = contentCollectionView.collectionViewLayout as!
UICollectionViewFlowLayout
layout.scrollDirection = .Vertical
}
}
Normally a collectionView is dropped in storyboard from object library, it automatically comes with FlowLayout. You can change this layout's flow direction by telling your code that when I get my collection view, I want its layout's scroll direction to be horizontal or vertical.

UICollectionView cell disappears

I am using collectionView in my iPad application. I have used custom layout class which inherited UICollectionViewFlowLayout class.
I am using horizontal scroll directional. The problem is, whenever we use scroll for collection view, some times cell get disappear. I debugged the code, and found that in data source method after creating cell, its hidden property get automatically ON.
I tried using below line but its not working
cell.hidden = NO
I have below method also to invalidate layout on bound change.
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
But still I am facing problem. Any solution on this ?
Thanks in advance.
There is a known issue which may cause cells to disappear in UICollectionView. If their fix doesn't work for you, try PSTCollectionView,
which is an open source replacement for UICollectionView. If PSTCollectionView works, you should file a radar ticket to Apple.
In my project, the UICollectionViewCell disappear also ,the flowLayout i use is a custom layout named UICollectionViewLeftAlignedLayout . Its scroll direction is horizontal .I debug the project again and again, have tried every solution i can find through google.com. All that did not work for me.
At the end ,i delete the UICollectionViewLeftAlignedLayout and use native
UICollectionViewFlowLayout through:
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
_collectionView.collectionViewLayout = layout;
_CollectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
And I set the cell spacing through storyboard(also you can set them through the layout's propery):
Then i run the project again , the UICollectionViewCell DO NOT DISAPPEAR anymore. Hope my case can help you .

UICollectionView's cell disappearing

What's happening
Currently I have an application that uses two UICollectionViews inside a UITableView. This way I create a Pulse News look like application. My problem with this is that sometimes the 6th and 11th row disappears completely, leaving a blank space where it should be the cell. I wouldn't actually mind, if all the cells were like this (and this way I could assume that I wasn't doing things correctly), but the thing is, is just happening with those specific ones.
My theory
The 6th and 11th rows are the ones that appears when I start scrolling, so by default I am able to see 5 cells, and when I do the first horizontal scrolling the 6th comes up (blank space sometimes).
What I have
The only thing I am doing at the moment is this:
[self.collectionView registerNib:[UINib nibWithNibName:CELL_NIB_NAME bundle:nil] forCellWithReuseIdentifier:CELL_IDENTIFIER];
On the viewDidLoad. And on the creation of the cell:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER forIndexPath:indexPath];
NSMutableDictionary *dictionary = [self.DataSource objectAtIndex:[indexPath row]];
[cell buildViewWithDictionary:dictionary withReferenceParent:self.referenceViewController];
return cell;
}
So on my understating nothing fancy going on here. I though there was something wrong on the data source (a dummy JSON file), but sometimes it works ok and the cell shows, so I guess from that part is ok.
So my "question": Does anyone knows what's going on? I don't really like to say that it's a bug from iOS, but I can't think of anything else.
Edit 1.0
The amazing part is that this method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
Is going from indexPath [0,4] to [0,6] without calculating the [0,5]. First time I actually see this happening in iOS.
Edit 2.0
I have switched the way I am creating the cells, and instead of dequeuing I am using the old way:
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CELL_NIB_NAME owner:self options:nil];
MyCell *cell = (MyCell *)[nib objectAtIndex:0];
Still the same sad result.
So, what did work?
1) Subclass UICollectionViewFlowLayout.
2) Set the flowLayout of my UICollectionView to my new subclass.
3) On the init method of the UICollectionViewFlowLayout subclass, set the orientation you want:
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
In my case it is Horizontal.
4) The important part:
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
At this moment, I should theorise a bit, but honestly I don't have a clue.
The above answers didn't work for me, but after downloading the images, I replaced the code
[self.myCollectionView reloadData]
with
[self.myCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
to refresh the collectionview and it shows all cells, you can try it.
None of the solutions given by anyone helped me in my custom layout that we need to have in our app.
Instead, I had to do this: (And yeah, IT WORKS!!!)
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
CGSize size = [self collectionViewContentSize];
rect.size.height = size.height*2;
NSArray *atrributes_Super = [super layoutAttributesForElementsInRect:rect];
return atrributes_Super;
}
After all, UICollectionView is just looking for the attributes for the elements to be displayed in your screen's rect.
Rob's tip about the bug helped me. The bug states that if the section insets and cells widths and spacing add up exactly to the width of the screen then the first column sometimes randomly dissappears and reappears for some cells in some places. Rather than subclass or change the cell widths, I changed the section insets for left and right in my storyboard from 6 to 4 and it I haven't seen the problem again.
As I run the same problem suddenly and spent some time figuring out one of possible reasons of cell disappearing during the scroll, I will add my answer as well.
Prerequisites of the problem:
You have a UICollectionView instance
You have a UICollectionViewFlowLayoutSubclass
The problem
Cells disappear from the Collection View after scrolling to the certain point.
The source of the problem is in wrong subclassing of the UICollectionViewFlowLayout.
As it explicitly said in documentation:
Every layout object should implement the following methods:
- collectionViewContentSize
- layoutAttributesForElements(in:)
- layoutAttributesForItem(at:)
- layoutAttributesForSupplementaryView(ofKind:at:) // (if your layout supports -supplementary views)
-layoutAttributesForDecorationView(ofKind:at:) // (if your layout supports decoration views)
- shouldInvalidateLayout(forBoundsChange:)
By relying on UICollectionViewFlowLayout implementation of methods above we miss the fact, that func layoutAttributesForElements(in rect: CGRect) and collectionViewContentSize will generate wrong contentSize (the size that would be correct if all the cells would have itemSize size and the content size would be corresponding. As soon as scroll offsetY will be greater that contentSize height cell will all disappear.
The solution
The solution is in proper UICollectionViewFlowLayout subclassing. Override all the methods that are required to override and everything will work just fine.
In my case (vertical scroll, with cells disappearing in first view), cells were disappearing due to incorrect estimated size. It seems, UICollectionView uses the estimated size to calculate the items to load in first view. I'd set the estimated size too high which was resulting in wrong calculations for number of items to load in first screen.
The moment I made the estimated height bit low, all the cells appeared correctly.
We ran into disappearing cells recently and found that rather than skipping 'hidden' cells we were accidentally inserting 0x0 sized cells. The resulting behavior was very confusing and did not suggest these invisible cells were the issue. We would see the correctly sized cells and layout, but a few of the valid cells would consistently disappear after scrolling off/on screen. I have no idea why intermingling 0 sized cells would cause this behavior, but removing them fixed the problem. This may not be causing your problem, but this may be helpful to devs searching for similar symptoms.
Just ran into an issue where all UICollectionView cells were disappearing on scroll.
This happened because I had declared
extension UICollectionViewLayout {
static let defaultLayout: UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
return layout
}()
}
... meaning the same layout instance was being used in multiple UICollectionViews. I had meant to make that a computed var. Hope this helps someone who's accidentally using the same layout object in multiple collection views.
What caused the cells to disappear in my case was that the data source was being deallocated prematurely. UICollectionView.dataSource is a weak property, which means that unless you keep a strong reference to it, the object will be deallocated at the end of the scope in which you created. The problem manifested itself with disappearing cells as soon as I tapped on the UICollectionView.
For me this issue seemed to be related with the way i make my collectionview adapt to an open keyboard to prevent content overlaps.
in my observer to respond to KeyboardWillShow i had this:
var userInfo = obj.UserInfo[UIKeyboard.FrameEndUserInfoKey];
if (userInfo is NSValue value)
{
var rect = value.CGRectValue;
var windowOffset = this.Superview.ConvertPointToView(this.Frame.Location, UIApplication.SharedApplication.KeyWindow);
var newHeight = rect.Y - windowOffset.Y;
this._controller.CollectionView.Frame = new CGRect(0, 0, this._controller.CollectionView.Frame.Width, newHeight);
}
After changing it to this:
var userInfo = obj.UserInfo[UIKeyboard.FrameBeginUserInfoKey];
if (userInfo is NSValue value)
{
var rect = value.CGRectValue;
UIEdgeInsets contentInsets = new UIEdgeInsets(0, 0, rect.Height, 0);
this._controller.CollectionView.ContentInset = contentInsets;
this._controller.CollectionView.ScrollIndicatorInsets = contentInsets;
}
The cell disappearance issue completely went away. This is C# from working with xamarin but i hope it helps someone else.
I think this is not a UICollectionView‘s bug, maybe your not return right data in - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect method.
You can see this demo: https://github.com/lqcjdx/YLTagsChooser , all cells can appear when scolling the UICollectionView.

Resources