Photo gallery with a CollectionView xcode - ios

I am building an application that looks like a Photo Gallery.
I follow different references, but It still not run.
The problem is with the imageView in the cell, because if I try to change the backgroundColor of the cell it works, in spite of if I try to change the image of the imageView it doesn't run.
- (void)viewDidLoad {
[super viewDidLoad];
_ownImages = [#[#"1.jpg",
#"2.jpg",
#"2.jpg",
#"3.jpg"] mutableCopy];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
_photoGallery =[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_photoGallery setDataSource:self];
[_photoGallery setDelegate:self];
[_photoGallery registerClass:[PhCell class] forCellWithReuseIdentifier:#"photoCell"];
[self.view addSubview:_photoGallery];
}
Here I change the option of the CollectionView
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(100, 100);
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _ownImages.count;
}
And finally, I create the Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PhCell *myCell = [_photoGallery dequeueReusableCellWithReuseIdentifier:#"photoCell" forIndexPath:indexPath];
long row = [indexPath row];
NSLog(#"%#", _ownImages[row]);
image = [UIImage imageNamed:_ownImages[row]];
myCell.backgroundColor = [UIColor clearColor];
myCell.imageView.image = image;
return myCell;
}
To implement the custom Cell I create an UICollectionViewCell called PhCell. In this Class I set an xib file for the cellView in which there is an imageView connected to the variable
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
in PhCell.h
The code is free of errors, but it not display the image, why?

Just try to set the imagebackground is another color, like yellow, and let see the image is shown or not.
In the line image = [UIImage imageNamed:_ownImages[row]]; I can see you have not inited the image.

Related

CollectionView Horizontal scroll not working in ios 7

CollectionView horizontal scroll not working in ios 7 but it's working fine in ios 8 and 9. Is there any solution for this ?
The Code is here:
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.itemSize = CGSizeMake(330, 100);
collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0.0, 50.0, 350, 100) collectionViewLayout:layout];
collection.delegate = self;
collection.dataSource = self;
collection.backgroundColor = [UIColor greenColor];
collection.pagingEnabled = YES;
[collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"Cell"];
[self.view addSubview:collection];
It now fits my needs, and could be useful for someone else, so here is my code:
I have tested In iOS7-8-9. Below example is for Default iPad. You Just need to change target settings and O.S Version.
https://github.com/philippeauriach/fullyhorizontalcollectionview
Please download it & let us know ur comments. Happy Coding!
If you want to add collection view onto the View then use below code. Below code into i have created CL View programmatically and It's also working correctly with Autolayout and iOS 7-8-9. Please implement below code and let us know ur comments.
.H File
#interface HorizontalCollectionViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>{
NSIndexPath *visibleIndexPath;
}
#property (nonatomic, assign) NSInteger selectedCell;
#property (strong, nonatomic) IBOutlet UICollectionView *horizonCLView;
.M File
#import "HorizontalCollectionViewController.h"
static NSString * const CellIdentifier = #“horizonCell";
#interface HorizontalCollectionViewController ()
#end
#implementation HorizontalCollectionViewController
#synthesize horizonCLView;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"view frame : %#",NSStringFromCGRect(self.view.frame));
[self.view layoutIfNeeded];
[self.view setNeedsLayout];
[self viewDidLayoutSubviews];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
layout.itemSize = self.view.frame.size;
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[layout setMinimumInteritemSpacing:0.f];
[layout setMinimumLineSpacing:0.f];
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
horizonCLView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
horizonCLView.dataSource = self;
horizonCLView.delegate = self;
horizonCLView.backgroundColor = [UIColor lightGrayColor];
horizonCLView.scrollEnabled = YES;
[horizonCLView setBounces:NO];
[horizonCLView setUserInteractionEnabled:YES];
[horizonCLView setPagingEnabled:YES];
[horizonCLView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CellIdentifier];
[self.view addSubview:horizonCLView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewWillAppear:(BOOL)animated{
//Select Current Image For Sare In Social Media
// currentImageIndex = selectedCell;
[horizonCLView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:selectedCell inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
CGRect visibleRect = (CGRect){.origin = self.horizonCLView.contentOffset, .size = self.horizonCLView.bounds.size};
CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
visibleIndexPath = [self.horizonCLView indexPathForItemAtPoint:visiblePoint];
// NSLog(#"visibleIndexPath.row in View will appear %ld",(long)visibleIndexPath.row);
//SelectedCell is a selected image from gallary view
NSLog(#"selectedCell in View will appear: %ld",(long)selectedCell);
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [dataAry count];
}
#pragma Here we set the frame of horizontal scrll view
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
// expand cell to fill the entire view
return collectionView.frame.size;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
self.title = [[self.dataAry objectAtIndex:indexPath.row] valueForKey:#“dataAryName"];
//imageVI.image = nil;
imageVI = (UIImageView *)[cell.contentView viewWithTag:100];
if (!imageVI){
imageVI = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height)];
imageVI.contentMode = UIViewContentModeScaleAspectFill;
imageVI.tag = 100;
imageVI.clipsToBounds = YES;
[cell.contentView addSubview:imageVI];
}
dispatch_async(dispatch_get_main_queue(), ^{
[asSetLib assetForURL:[NSURL URLWithString:[[self.dataAry objectAtIndex:indexPath.row] valueForKey:#"dataAryName"]] resultBlock:^(ALAsset *asset) {
// imageVI.image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
imageVI.image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullResolutionImage];
NSLog(#"Preview view into album loaded successfully!");
} failureBlock:^(NSError *error) {
NSLog(#"An error occurred while loading image: %#", error.description);
}];
});
return cell;
}
Sudha, I think this issues in your code not an iOS7 issues.
Here, I have review two bug in ur code.
1)In this line you have give static width of collection view,
collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0.0, 50.0, 350, 100) collectionViewLayout:layout];
Instead Of it will be goes look like,
collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0.0, 50.0, self.view.bounds.size.width, 100) collectionViewLayout:layout];
Make sure your collection view width size always go with according to your view size.
2)Make sure, Your layout item size width higher then collection view width frame. Otherwise Scrolling was not effected.
layout.itemSize = CGSizeMake(self.view.bounds.size.width+10, 100);
3) Carefully use,
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
delegate method of collectionview layout size method.
4)Finally your code look like,
- (void)viewDidLoad {
[super viewDidLoad];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
layout.itemSize = CGSizeMake(self.view.bounds.size.width+10, 100);
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0.0, 50.0, self.view.bounds.size.width, 100) collectionViewLayout:layout];
collection.delegate = self;
collection.dataSource = self;
collection.backgroundColor = [UIColor greenColor];
collection.pagingEnabled = YES;
collection.scrollEnabled = YES;
collection.userInteractionEnabled = YES;
[collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"Cell"];
[self.view addSubview:collection];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
return cell;
}
Happy Coding!
I've used a line of code after adding collectionView on view that its working fine in ios 7 also.
add this code after [self addSubview:self.collectionView];
here the code:
[self performSelector:#selector(update) withObject:nil afterDelay:1];
(void)update {
[self.collectionView setContentOffset:CGPointMake(1, 0)];
}

How to fix UICollectionViewCell with UIImageView Overlap Programmatically

I'm create UICollectionView programmatically to uiview (i use single view). like this
UICollectionViewFlowLayout *CATLayout=[[UICollectionViewFlowLayout alloc]init];
CATLayout.minimumInteritemSpacing = 2.0f;
CATLayout.minimumLineSpacing = 2.0f;
CATLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
CATLayout.sectionInset = UIEdgeInsetsMake(1.0f, 1.0f, 1.0f, 1.0f);
self.ColStickersListView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, StickersListView.frame.size.width, StickersListView.frame.size.height) collectionViewLayout:CATLayout];
self.ColStickersListView.delegate=self;
self.ColStickersListView.dataSource=self;
self.ColStickersListView.tag=2;
[self.ColStickersListView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"CollStickersList"];
[self.ColStickersListView setBackgroundColor:[UIColor clearColor]];
[StickersListView addSubview:ColStickersListView];
and
UICollectionViewCell *cell = [ColStickersListView dequeueReusableCellWithReuseIdentifier:#"CollStickersList" forIndexPath:indexPath];
// for background selected
NSString *imageName=anObject;
NSString *filename=[NSString stringWithFormat:#"%#/Stickers/List/%#",[appDel DocsPath],imageName];
NSLog(#"%#",filename);
cell.backgroundColor=[UIColor clearColor];
UIImage *image=[UIImage imageNamed:filename];
UIImageView *photoView=[[UIImageView alloc]initWithFrame:CGRectMake(StickersListPadding,StickersListPadding,StickersListThumbSize-(StickersListPadding*2),StickersListThumbSize-(StickersListPadding*2))];
photoView.image=image;
photoView.contentMode=UIViewContentModeScaleAspectFit;
photoView.userInteractionEnabled = YES;
[cell.contentView addSubview:photoView];
return cell;
it's work perfect for display image to cell.
Problem !!
if scroll page to bottom and scroll return to top again that image in cell it's overlap.
How to fix it.!!! (Programmatically only with single view)
I suspect because you aren't setting the frame on the UIImageView it is deriving its size from the image that is being set on it. So in some cases it might overflow its parent view -> the cell in this case.
I suggest you setup some constraints on the UIImageView, this can be done programmatically.
So try to set left, right, top and bottom constraints on the UIIMageView so that it stays within the bounds of the cell
During scroll
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath is beeing called repeatively..
the means your are adding UIImageView *photoView repeatedly to cell.contentView
UIImageView *photoView=[[UIImageView alloc]initWithFrame:CGRectMake(StickersListPadding,StickersListPadding,StickersListThumbSize-(StickersListPadding*2),StickersListThumbSize-(StickersListPadding*2))];
//codes..
[cell.contentView addSubview:photoView];
doing something like this prevent that:
UICollectionViewCell *cell = [ColStickersListView dequeueReusableCellWithReuseIdentifier:#"CollStickersList" forIndexPath:indexPath];
if (cell == nil)
{
UIImageView *photoView=[[UIImageView alloc]initWithFrame:CGRectMake(StickersListPadding,StickersListPadding,StickersListThumbSize-(StickersListPadding*2),StickersListThumbSize-(StickersListPadding*2))];
// codes...
[cell.contentView addSubview:photoView];
}
Another way of solving this is by creating a custom collection cell:
// CustomCollectionCell.h
#interface YourCollectionCell : UICollectionViewCell
#property (nonatomic) UIImageView *photoView;
#end
// CustomCollectionCell.m
#implementation YourCollectionCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// and setting up you imageview here
self.photoView=[[UIImageView alloc]initWithFrame:YourRect];
self.photoView.contentMode=UIViewContentModeScaleAspectFit;
self.photoView.userInteractionEnabled = YES;
[self.contentView addSubview:self.photoView];
}
return self;
}
and using it like:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCollectionCell *cell = (CustomCollectionCell *)[ColStickersListView dequeueReusableCellWithReuseIdentifier:#"CollStickersList" forIndexPath:indexPath];
cell.photoView.image=image;
return cell;
}
Hope i've helped you, happy coding.. Cheers & Good night!

How to add photos into UICollectionViewCell?

I have creates a UICollectionView which I currently have showing white cells. I have been following this tutorial to figure out how to use the delegate methods etc.
I have made it up to the point where you create the Creating custom UICollectionViewCells however in this example the tutorial he tells you to open your story board etc. I don't have a story board. I have tried to follow the instructions to create the view but with my own .xib file and I just cannot get anything to work.
How can I check out where my delegate methods are at this point?
// this is how I load the collection view
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
photoCollectionView =[[UICollectionView alloc] initWithFrame:CGRectMake(10.0, 40.0, 480.0, 713.0) collectionViewLayout:layout];
photoCollectionView.dataSource = self;
photoCollectionView.delegate = self;
[self.view addSubview:photoCollectionView];
[photoCollectionView.layer setBorderColor: [[UIColor lightGrayColor] CGColor]];
[photoCollectionView.layer setBorderWidth: 1.0];
[self.photoCollectionView reloadData];
// this is what my delegate methods look like
#pragma mark - CollectionView Delegates
#pragma mark -- UICollectionView Datasource
// 1
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
return [imageArray count];
}
// 2
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 1;
}
// 3
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"PhotoCell" forIndexPath:indexPath];
// I think this is where I want to set my image for the cell
NSDictionary *currentPhotoDict = [imageArray objectAtIndex:indexPath.row];
UIImage *imageForCollection = [UIImage imageWithData:[currentPhotoDict objectForKey:#"DImage"]];
// but I have no idea where to pass the imag....
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
#pragma mark -- UICollectionView Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// TODO: Select Item
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
// TODO: Deselect item
}
#pragma mark –- UICollectionViewDelegate FlowLayout
// 1
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize retval = CGSizeMake(210, 157+20); // add 20 for labels under neath.. might need to adjust this.
return retval;
}
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(50, 20, 50, 20);
}Subview:photoCollectionView];
[photoCollectionView.layer setBorderColor: [[UIColor lightGrayColor] CGColor]];
[photoCollectionView.layer setBorderWidth: 1.0];
[self.photoCollectionView reloadData];
As you can see in collectionView:cellForItemAtIndexPath I have my image ready
NSDictionary *currentPhotoDict = [imageArray objectAtIndex:indexPath.row];
UIImage *imageForCollection = [UIImage imageWithData:[currentPhotoDict objectForKey:#"DImage"]];
I just need to know how to load it into the collectionviewcell.
Please try to use like this....
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"PhotoCell" forIndexPath:indexPath];
// I think this is where I want to set my image for the cell
NSDictionary *currentPhotoDict = [imageArray objectAtIndex:indexPath.row];
UIImage *imageForCollection = [UIImage imageWithData:[currentPhotoDict objectForKey:#"DImage"]];
[cell setBackgroundColor:[UIColor colorWithPatternImage:imageForCollection];// Add your image here........
// but I have no idea where to pass the imag....
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
i hope it will help you...
I have UICollectionViewCell with name PhotoCell. and have label and imageview as properties.
This is how u can set Image to cell. May this is your requirement or not. I dont know. Try this
You need to set identifier at Xib of your UICollectionViewCell as MY_CELL or some other name.Then
.m
static NSString *cellidentity=#"MY_CELL";
At ViewDidLoad method
UINib *nib;
nib = [UINib nibWithNibName:#"PhotoCell" bundle:nil];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:cellidentity];
My UICollectionViewCell .h is
#interface PhotoCell : UICollectionViewCell
#property (retain, nonatomic) IBOutlet UILabel* label;
#property (retain, nonatomic) IBOutlet UILabel* timelineLabel;
#property (retain, nonatomic) IBOutlet UIImageView* yourImageView;
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
// PhotoCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"PhotoCell" //forIndexPath:indexPath];
PhotoCell *cell = [cv dequeueReusableCellWithReuseIdentifier:cellidentity forIndexPath:indexPath];
NSDictionary *currentPhotoDict = [imageArray objectAtIndex:indexPath.row];
UIImage *imageForCollection = [UIImage imageWithData:[currentPhotoDict objectForKey:#"DImage"]];
// but I have no idea where to pass the imag....
cell.label.text = [NSString stringWithFormat:#"%d",indexPath.item];
cell.yourImageView.image=imageForCollection;
return cell;
}
Hope it helps You....

Change attributes of a UICollectionViewCell in didSelectItemAtIndexPath

I am configuring a UICollectionViewCell in a subclass, it adds 2 subviews to the contentView property, both are UIImageView and both have the hidden property set to YES. These subviews are "checked" and "unchecked" images that overlay the primary UIImageView in the cell to indicate whether or not the current cell is selected using UICollectionView's "multiple select" feature.
When the cell is tapped, collectionView:didSelectItemAtIndexPath: is called on the delegate, and I'd like to setHidden:NO on the "checked" UIImageView. Calling this on the cell does nothing at all -- the cell is seemingly locked in its originally drawn state.
Is it possible to make changes to a cell outside collectionView:cellForItemAtIndexPath:? I have tried manually adding subviews within collectionView:didSelectItemAtIndexPath:, but it just makes absolutely no change to the UI. I have verified that the delegate method is getting called, it's just not making my cell changes.
- (void) collectionView(UICollectionView *)cv didSelectItemAtIndexPath(NSIndexPath *)indexPath {
ShotCell *cell = [self collectionView:cv cellForItemAtIndexPath:indexPath];
UILabel *testLabel = UILabel.alloc.init;
testLabel.text = #"FooBar";
testLabel.sizeToFit;
[cell.contentView.addSubview testLabel];
}
The way you're trying to do this is incorrect. You need to keep a reference to the selected cell or cells in a property. In this example, I use an array to hold index paths of the selected cells, then check whether the index path passed in to cellForItemAtIndexPath is contained in that array. I unselect the cell if you click on one that's already selected:
#interface ViewController ()
#property (strong,nonatomic) NSArray *theData;
#property (strong,nonatomic) NSMutableArray *paths;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.paths = [NSMutableArray new];
self.theData = #[#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight"];
[self.collectionView registerNib:[UINib nibWithNibName:#"CVCell" bundle:nil] forCellWithReuseIdentifier:#"cvCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView setCollectionViewLayout:flowLayout];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.theData.count;
}
-(CVCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cvCell";
CVCell *cell = (CVCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
cell.label.text = self.theData[indexPath.row];
if ([self.paths containsObject:indexPath]) {
[cell.iv setHidden:NO]; // iv is an IBOutlet to an image view in the custom cell
}else{
[cell.iv setHidden:YES];
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
if ([self.paths containsObject:indexPath]) {
[self.paths removeObject:indexPath];
}else{
[self.paths addObject:indexPath];
}
[self.collectionView reloadItemsAtIndexPaths:#[indexPath]];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(150, 150);
}

subView in UICollectionViewCell displayed wrong when UICollectionView scrolled

I make a custom UICollectionViewCell and add a subView to its contentView:
BooksCell.h
#interface BooksCell : UICollectionViewCell
#property (strong, nonatomic) UIImageView *certifyImageView;
#end
BooksCell.m
- (id)initWithFrame:(CGRect)frame {
self= [super initWithFrame:frame];
if(self){
_coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 15, 88, 117)];
_coverImageView.userInteractionEnabled = YES;
[self.contentView addSubview:_coverImageView];
UIImage *certifyImage = [UIImage imageNamed:#"13-6.png"];
_certifyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(17.5, _coverImageView.frame.size.height-3, certifyImage.size.width, certifyImage.size.height)];
_certifyImageView.image = certifyImage;
_certifyImageView.hidden = YES;
}
return self;
}
ViewController
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
BooksCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"BooksCell" forIndexPath:indexPath];
cell.coverImageView.image = [UIImage imageNamed:#"13-5.png"];
// **Here I want some cell display certifyImageView and some not.**
if(indexPath.row%2==0){
cell.certifyImageView.hidden = NO;
}
return cell;
}
I add the collectionView as subView to the Viewcontroller, and set it's frame correctly, now the collectionView displaied coverImageView and certifyImageView normally, but when I scroll the collectionView, certifyImageView displaied on the wrong cell,I guess it maybe caused by the Reuse Cell, and how to sole it?
I think because it is reusing the cell that already set the certifyImageView.hidden to NO so you have to set it back to YES
Maybe try this
if(indexPath.row%2==0){
cell.certifyImageView.hidden = NO;
}
else{
cell.certifyImageView.hidden = YES;
}
This way you will make sure that the certifyImageView will be set to hidden if thats what you want.

Resources