Im using UICollectionView for my project. But i get some issue with it: cellForItemAtIndexPath is not working when i call reloadData and scroll. This is my code:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [listImage count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView1 cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"indexpath %d", indexPath.row);
NSString *cellIdentify = #"HomeCollectionViewCell";
HomeCollectionViewCell *cell = (HomeCollectionViewCell *)[collectionView1 dequeueReusableCellWithReuseIdentifier:cellIdentify forIndexPath:indexPath];
NSMutableDictionary *dictionary = [listImage objectAtIndex:indexPath.row];
//set image pop-up for first time login
UIImageView *imageViewSignUp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon_popupSignUp.png"]];
if (indexPath.row == 5 && ![IQUser currentUser]) {
imageViewSignUp.frame = CGRectMake(120, self.view.frame.size.height-100, 60, 63);
[self.view addSubview:imageViewSignUp];
}
//set data for product or share
[cell.contentView setUserInteractionEnabled:YES];
NSString *string = [[dictionary objectForKey:kDetail] objectForKey:kImage];
if ([string rangeOfString:#"http://"].location != NSNotFound) {
[self setImageWithString:cell.imageView aURL:string];
} else {
cell.imageView.image = [UIImage imageNamed:string];
}
return cell;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
}
-(CGSize)collectionView:(UICollectionView *)collectionView1 layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize size = collectionView.frame.size;
return size;
}
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
}
it is a issue on collectionView?!
What is not working with UICollectionView ? please specify your problem.
And why are you setting image on UIView in cellForItemAtIndexPath
UIImageView *imageViewSignUp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon_popupSignUp.png"]];
if (indexPath.row == 5 && ![IQUser currentUser]) {
imageViewSignUp.frame = CGRectMake(120, self.view.frame.size.height-100, 60, 63);
[self.view addSubview:imageViewSignUp];
}
Related
how to bind data from server into collectionview which is inside uitableviewcell using hide and unhide functionality.on tap of uibutton i want to make colectionview visible and hide it again on the tap of button.What happens is when i scroll the tableview the data inside the collectionview skips from one cell to another making the collection view blank.
-(void)arrowButtonTapped:(UIButton *)donwbtn{
myob = [NSString stringWithFormat:#"%li", (long)donwbtn.tag];
NSLog(#"%#",myob);
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0
inSection:donwbtn.tag];
OppCell* celll = [_tableView cellForRowAtIndexPath:indexPath];
celll.collView.tag=donwbtn.tag;
if ([checkcoll containsObject:myob]) {
[checkcoll removeObject:myob];
celll.collView.hidden = true;
celll.collvwhght.constant=0;
celll.colltop.constant=0;
celll.collbottom.constant=0;
}
else
{
[checkcoll addObject:myob];
celll.collView.hidden = false;
celll.collvwhght.constant=229;
celll.colltop.constant=9;
celll.collbottom.constant=8;
[celll.collView reloadData] ;
}
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
OppCell *cell = (OppCell *)[tableView
dequeueReusableCellWithIdentifier:#"OppCell"];
NSString *theIndexpath = [NSString stringWithFormat:#"%ld",
(long)indexPath.section];
if ([checkcoll containsObject:theIndexpath])
{
cell.collView.hidden = false;
cell.collvwhght.constant=229;
cell.colltop.constant=9;
cell.collbottom.constant=8;
if((![[[_Activitylistarray
objectAtIndex:indexPath.section]
valueForKey:#"OpportunityContactInfoList"]
isKindOfClass:[NSNull class]])&&([[[_Activitylistarray
objectAtIndex:indexPath.section]
valueForKey:#"OpportunityContactInfoList"]count]>0)){
if(cell.contactdetailsarray == nil) {
cell.contactdetailsarray =[[NSMutableArray alloc]init];
for(NSDictionary * contactdict in
[[_Activitylistarray objectAtIndex:indexPath.section]
valueForKey:#"OpportunityContactInfoList"] ){
[cell.contactdetailsarray addObject:contactdict];
[cell.collView reloadData];
}
}
}
}
else
{
cell.collView.hidden = true;
cell.collvwhght.constant=0;
cell.colltop.constant=0;
cell.collbottom.constant=0;
// [cell.contactdetailsarray removeAllObjects];
// [cell.collView reloadData];
}
////Code in UITableViewCell
#import "OppCell.h"
#import "OppsContactCell.h"
#implementation OppCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
[self.collView registerNib:[UINib nibWithNibName:#"OppsContactCell"
bundle:nil] forCellWithReuseIdentifier:#"OppsContactCell"];
self.collView.pagingEnabled = YES;
UICollectionViewFlowLayout * layout=[[UICollectionViewFlowLayout
alloc]init];
layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
self.collView.collectionViewLayout = layout;
self.collView.decelerationRate =
UIScrollViewDecelerationRateNormal;
// _contactdetailsarray=[NSMutableArray array];
// self.collvwhght.constant=0;
//self.collView.hidden=YES;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (UICollectionViewCell *)collectionView:(UICollectionView
*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
OppsContactCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:#"OppsContactCell"
forIndexPath:indexPath];
cell.contactimgvw.image = [cell.contactimgvw.image
imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[cell.contactimgvw setTintColor:[UIColor blackColor]];
cell.numberimgvw.image = [cell.numberimgvw.image
imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[cell.numberimgvw setTintColor:[UIColor blackColor]];
cell.emailimgvw.image = [cell.emailimgvw.image
imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[cell.emailimgvw setTintColor:[UIColor blackColor]];
if(_contactdetailsarray.count==1){
if(([[[_contactdetailsarray
objectAtIndex:0]valueForKey:#"Designation"]isEqualToString:#""])&&([[[_contactdetailsarray
objectAtIndex:0]valueForKey:#"Department"]isEqualToString:#"" ])){
cell.lbldesignation.text=#"";
}
else{
cell.lbldesignation.text=[NSString stringWithFormat:#"%#,%#",
[[_contactdetailsarray objectAtIndex:0]valueForKey:#"Designation"],
[[_contactdetailsarray objectAtIndex:0]valueForKey:#"Department"]];
}
cell.lblcontatname.text=[[_contactdetailsarray
objectAtIndex:0]valueForKey:#"ContactName"];
cell.lblcontactnumber.text=[[_contactdetailsarray
objectAtIndex:0]valueForKey:#"TelephoneNo"];
cell.lblemail.text=[[_contactdetailsarray
objectAtIndex:0]valueForKey:#"EmailAddress"];
}
else{
if(([[[_contactdetailsarray
objectAtIndex:0]valueForKey:#"Designation"]isEqualToString:#""])&& .
([[[_contactdetailsarray
objectAtIndex:0]valueForKey:#"Department"]isEqualToString:#"" ])){
cell.lbldesignation.text=#"";
}
else{
cell.lbldesignation.text=[NSString stringWithFormat:#"%#,%#",
[[_contactdetailsarray
objectAtIndex:indexPath.section]valueForKey:#"Designation"],
[[_contactdetailsarray
objectAtIndex:indexPath.section]valueForKey:#"Department"]];
}
cell.lblcontatname.text=[[_contactdetailsarray
objectAtIndex:indexPath.row]valueForKey:#"ContactName"];
cell.lblcontactnumber.text=[[_contactdetailsarray
objectAtIndex:indexPath.row]valueForKey:#"TelephoneNo"];
cell.lblemail.text=[[_contactdetailsarray
objectAtIndex:indexPath.row]valueForKey:#"EmailAddress"];
}
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(_collView.bounds.size.width
,_collView.bounds.size.height);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 5;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section{
// return 5;
if(_contactdetailsarray.count==0){
return 0;
}
else{
return _contactdetailsarray.count;
}
}
Thanks & Regards,
Roshan.k
I have an UICollection View i am using the peek and pop method to look into it normally it works fine but if i use peek and pop i get the error
The code for the collection view class
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
AppsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
cell.titleLabel.text = #"TwitClient";
cell.iconimg.image = [UIImage imageNamed:#"twitclient"];
cell.appsbutton.userInteractionEnabled = NO;
cell.appsbutton.hidden = NO;
cell.appsbutton.alpha = 0.0;
cell.phoneImageView.image = [UIImage imageNamed:#"app3"];
cell.descLabel.text = #"TwitClient is an app which helps you find tweets on any subject from around the earth. You can search tweets with or without hashtags";
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(69, 126, 277, 490)];
imageView.image = [UIImage imageNamed:#"T-2"];
[cell addSubview:imageView];
return cell;
}
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(0, 0, 0, 0);
}
This is where 3d touch is implmented
- (UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
AppsViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"...."];
previewingContext.sourceRect = self.appsView.frame;
return appsvc;
}
- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
{
[self presentViewController:viewControllerToCommit animated:YES completion:nil];
}
I dont really know what i have done wrong i have done another collection View like this but no error's
I am pretty new in UICollectionView. And I am really tired to find out the solution. I am trying to add Header in 3 Horizontally Row. I am using Collection view flow layout.
Here is my code which I implement:
- (void)awakeFromNib {
self.collectionView.backgroundColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.0];
self.collectionView.backgroundColor = [UIColor clearColor];
self.collectionView.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.itemSize = CGSizeMake(130.0, 170.0);
[self.collectionView setCollectionViewLayout:flowLayout];
// Register the colleciton cell
[_collectionView registerNib:[UINib nibWithNibName:#"ORGArticleCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:#"ORGArticleCollectionViewCell"];
[self.collectionView registerClass:[_HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"HeaderView"];
}
#pragma mark - UICollectionViewDataSource methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if (section == 0) {
return [self.collectionData count];
}
else if(section == 1)
{
return [self.collectionData1 count];
}
else
{
return [self.collectionData2 count];
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
ORGArticleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ORGArticleCollectionViewCell" forIndexPath:indexPath];
cell.articleTitle.text = [self.collectionData objectAtIndex:[indexPath row]];
NSString *URL = [self.collectionImageData objectAtIndex:indexPath.row];
[cell.articleImage setImageWithURL:[NSURL URLWithString:URL] placeholderImage:[UIImage imageNamed:#"profile-image-placeholder"]];
cell.articleImage.contentMode = UIViewContentModeScaleToFill;
cell.articlePrice.text = [self.collectionDataPric objectAtIndex:[indexPath row]];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *cellData = [self.collectionData objectAtIndex:[indexPath row]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"didSelectItemFromCollectionView" object:cellData];
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 0;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
UICollectionElementKindSectionHeader withReuseIdentifier:#"HeaderView" forIndexPath:indexPath];
UILabel *label = (UILabel *)[headerView viewWithTag:10];
if (!label) {
label = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 5, 5)];
label.tag = 10;
label.font = [UIFont boldSystemFontOfSize:12];
label.textColor = [UIColor darkGrayColor];
[headerView addSubview:label];
}
label.text = [NSString stringWithFormat:#"Section %d", indexPath.section];
return headerView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
CGSize headerSize = CGSizeMake(320, 44);
return headerSize;
}
My App crash in viewForSupplementaryElementOfKind method when I initialize the header view.
Following are the crash log:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: UICollectionElementKindSectionHeader at path {length = 2, path = 0 - 0}'
The problem with your code is [headerView addSubview:label]; this is called only when label is equal to nil. but you have to call this statement every time when viewForSupplementaryElementOfKind is called.
Update your viewForSupplementaryElementOfKind function with following code.
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
UICollectionElementKindSectionHeader withReuseIdentifier:#"HeaderView" forIndexPath:indexPath];
UILabel *label = (UILabel *)[headerView viewWithTag:10];
if (!label) {
label = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 5, 5)];
label.tag = 10;
label.font = [UIFont boldSystemFontOfSize:12];
label.textColor = [UIColor darkGrayColor];
}
label.text = [NSString stringWithFormat:#"Section %d", indexPath.section];
[headerView addSubview:label];
return headerView;
}
I'm face a strange problem, when I execute from an action (button) the reloadData of my UICollectionView the cells are not displayed correctly, only the background image of the cells are ok.
My "INVPropertyCell" is composed with a background image and 2 labels (title & price). When I execute the reloadData the above labels from cells disappeared randomly.
I have done a lot of searches in the different forums, some people have the same problem but I didn't find out a fix.
Below, you will find my code, if someone can help me it would be very very appreciated.
Jérôme.
- (void)viewDidLoad
{
NSLog (#"INVPropertiesViewController -- viewDidLoad");
[super viewDidLoad];
// Enregistrement de la cellule.
[self.clProperties registerNib:[UINib nibWithNibName:#"INVPropertyCell" bundle:nil] forCellWithReuseIdentifier:#"propertyCell"];
// Enregistrement du header de section
[self.clProperties registerNib:[UINib nibWithNibName:#"INVPropertyHeaderSection" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"headerCollectionCell" ];
self.clProperties.delegate = self;
self.clProperties.dataSource =self;
NSLog (#"INVPropertiesViewController -- End of viewDidLoad");
}
- (void)viewWillAppear:(BOOL)animated
{
NSLog (#"INVPropertiesViewController -- viewWillAppear");
[super viewWillAppear:animated];
categoryDictionary = [ServiceDatas getCategoriesDictionary];
tblProperties = [(NSArray*)[ServiceDatas getListPropertiesByLieuFromLocalDataStore:self.selectedResidence] mutableCopy];
if(tblProperties.count==0 & self.selectedResidence.propertiesCount.longValue >0)
tblProperties = [(NSArray*)[ServiceDatas getListPropertiesByLieuFromServer:self.selectedResidence] mutableCopy];
tblPropertiesByCategory = [ServiceDatas createCategoryBreakDown:tblProperties];
keysCategories = [tblPropertiesByCategory allKeys];
[self.clProperties reloadData];
NSLog (#"INVPropertiesViewController -- End of viewWillAppear");
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
// [self.clProperties.collectionViewLayout invalidateLayout];
return tblPropertiesByCategory.count;
}
- (UICollectionReusableView *)collectionView: (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
UICollectionReusableView *reusableview = nil;
if(kind == UICollectionElementKindSectionHeader){
INVPropertyHeaderSection *headerSection = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"headerCollectionCell" forIndexPath:indexPath];
id categoryId = [keysCategories objectAtIndex:indexPath.section];
CategoryModel *category = categoryDictionary[categoryId];
if(category!=nil){
headerSection.backgroundColor = [Utils colorFromHexString:category.color];
headerSection.lblCategory.text = [category.title uppercaseString];
}
reusableview = headerSection;
}else if(kind == UICollectionElementKindSectionFooter){
if (reusableview==nil) {
reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}
}
return reusableview;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
// Return the number of rows in the section.
id categoryId = [keysCategories objectAtIndex:section];
NSMutableArray *tblProperties = [tblPropertiesByCategory objectForKey:categoryId];
return [tblProperties count];
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
INVPropertyCell *cell = nil;
id categoryId = [keysCategories objectAtIndex:indexPath.section];
NSMutableArray *tblProperties = [tblPropertiesByCategory objectForKey:categoryId];
if(tblProperties!=nil){
cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"propertyCell" forIndexPath:indexPath];
PropertyModel *property = [tblProperties objectAtIndex:indexPath.item];
NSLog(#"Ligne %ld - Colonne %ld - Lieux %#",indexPath.section, (long)indexPath.item, property.title );
CategoryModel *category = categoryDictionary[categoryId];
if(category!=nil){
[cell initWithProperty:property backgroundColor:[Utils colorFromHexString:category.color]];
}
}
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
// Récupération du bien courant.
id categoryId = [keysCategories objectAtIndex:indexPath.section];
NSMutableArray *tblProperties = [tblPropertiesByCategory objectForKey:categoryId];
PropertyModel *property = [tblProperties objectAtIndex:indexPath.row];
NSLog(#"Property sélectionnée : %#",property.title);
self.selectedProperty = property;
if(property!=nil && [property.title isEqualToString:EMPTY_PROPERTY]){
self.selectedProperty = nil;
}
// Déclenche le Segue pour aller à l'écran "Property"
[self performSegueWithIdentifier:#"segueEditPropertyView" sender:self];
}
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize mElementSize = CGSizeMake(107, 106);
if(indexPath.item==0){
mElementSize = CGSizeMake(106, 106);
}
return mElementSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 0.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 0.0;
}
// Layout: Set Edges
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(0,0,0,0); // top, left, bottom, right
}
- (IBAction)btnRefresh:(id)sender {
[self.clProperties reloadData];
}
i think,you have to register class before register nib for both INVPropertyCell and INVPropertyHeaderSection cell.
You try check and alloc cell if it is null in collectionView..cellForItemAtIndexPath
cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"propertyCell" forIndexPath:indexPath];
if (cell == null) {
Array *xibs = [[NSBundle mainBundle] loadNibWithNamed:#"propertycell"
...];
cell = xibs[0];
}
I'm coding in swift, so maybe above syntax is wrong, but this is idea :)
I have had a string of problems with UIcollectionView and I think the work around is what is currently causing the problem.
Okay, so I have a collectionview that loads objects from a class that updates very frequently, maybe every few seconds.
The first problem I ran into; was that when I selected a cell and highlighted it, another cell lower down on the collection view also became highlighted. My solution was to create an array of selectedcells and Run a loop through the new array to decide what to highlight.
Now, the problem arises when the collectionview is reloaded. The cells continue to stay highlighted and appear selected, but they do no register touches so I am unable to deselect it.
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection: (NSInteger)section
{
return [self.deviceList count];
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
DeviceCollectionViewCell *cell = [self.deviceCollectionView dequeueReusableCellWithReuseIdentifier:#"DeviceCell" forIndexPath:indexPath];
if([self.deviceList count] > indexPath.row)
{
cell.device = [self.deviceList objectAtIndex:indexPath.row];
}
if ([[self.deviceCollectionView indexPathsForSelectedItems] containsObject:indexPath]) {
NSLog(#"does it ever?");
// cell.backgroundColor = [UIColor blueColor];
}
for (TDDeviceParser *device in self.selectedDevices)
{
if ([cell.device.deviceTextRecord.serialNumber isEqualToString:device.deviceTextRecord.serialNumber])
{
[cell setSelected:YES];
break;
}
else
{
[cell setSelected:NO];
}
}
return cell;
}
- (UICollectionReusableView *)collectionView: (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableview = nil;
if (kind == UICollectionElementKindSectionHeader) {
TitleHeaderForDeviceCollectionView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"HeaderView" forIndexPath:indexPath];
reusableview = headerView;
}
else if (kind == UICollectionElementKindSectionFooter) {
LogoFooterForDeviceCollectionView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:#"FooterView" forIndexPath:indexPath];
reusableview = footerView;
}
return reusableview;
}
#pragma mark - UICollectionViewDelegate
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//Iphone Five and Older Ipads: Max2
int maxCount = 2;
//ipad 4
if ([[UIDeviceHardwareVersion platform] isEqualToString:#"iPad3,4"] || [[UIDeviceHardwareVersion platform] isEqualToString:#"iPad3,5"] || [[UIDeviceHardwareVersion platform] isEqualToString:#"iPad3,6"])
{
maxCount = 4;
}
//Ipod5th,Iphone4 & Iphone4s; Don't select, just play.
else if ([[UIDeviceHardwareVersion platform] isEqualToString:#"iPod5,1"] || [[UIDeviceHardwareVersion platform] isEqualToString:#"iPhone4,1"] || [[UIDeviceHardwareVersion platform] isEqualToString:#"iPhone3,1"] || [[UIDeviceHardwareVersion platform] isEqualToString:#"iPhone3,2"] || [[UIDeviceHardwareVersion platform] isEqualToString:#"iPhone3,3"])
{
maxCount = 0;
//Just play.
[self.selectedDevices removeAllObjects];
[self.selectedDevices addObject:[self.deviceList objectAtIndex:indexPath.row]];
[[TDDeviceManager sharedInstance] removeObserver:self];
[self performSegueWithIdentifier:#"VideoPlayer" sender:self];
}
if (self.selectedDevices.count < maxCount)
{
return YES;
}
else
{
return NO;
}
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.selectedDevices addObject:[self.deviceList objectAtIndex:indexPath.row]];
[self updatePlayerImages];
NSLog(#"device Count %d",self.selectedDevices.count);
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Should I Deselect?");
return YES;
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%s",__PRETTY_FUNCTION__);
//What device do we remove?
for (TDDeviceParser *device in self.selectedDevices)
{
if ([device.deviceTextRecord.serialNumber isEqualToString:((TDDeviceParser*)[self.deviceList objectAtIndex:indexPath.row]).deviceTextRecord.serialNumber])
{
NSLog(#"%s Removed %#",__PRETTY_FUNCTION__, device.name);
[self.selectedDevices removeObject:device];
break;
}
}
NSLog(#"%s Update %d",__PRETTY_FUNCTION__, self.selectedDevices.count);
[self updatePlayerImages];
}
I think the problem is that the cell was selected but the CollectionView didn't know that the cell was selected. I added(The Second Line) to fix the problem.
[cell setSelected:YES];
[self.deviceCollectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];