Instances of UICollectionViewCell showing behind other instances of UICollectionView - ios

To preface, I have some experience with iOS development, but this is my first app that I am going to publish to the AppStore, and also my first experience utilizing UICollectionView.
Here is a summary of what I am doing in my app:
I have a paged UICollectionView which contains several fullscreen UICollectionViewCells. Within each of these cells is another UICollectionView ('subCollectionView'), containing UICollectionViewCells ('subCollectionViewCells') which currently have their label set to "Test Text". When scrolling to the second collectionViewCell, the subCollectionViewCells of the first collectionViewCell are visible behind the second collectionViewCell's subCollectionView. I have linked the images to what is happening here.
The CollectionViewCell that includes the subCollectionView:
[VLCategoryCollectionViewCell.h]
#import <UIKit/UIKit.h>
#interface VLCategoryCollectionViewCell : UICollectionViewCell
#property (nonatomic, strong) NSString *imageName;
#property (strong, nonatomic) IBOutlet UIView *moduleSubview;
- (void)updateCell;
#end
[VLCategoryCollectionViewCell.m]
#import "VLCategoryCollectionViewCell.h"
#import "VLModuleViewController.h"
#interface VLCategoryCollectionViewCell()
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UILabel *categoryName;
#property (strong, nonatomic) VLModuleViewController *moduleViewController;
#end
#implementation VLCategoryCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle]
loadNibNamed:#"VLCategoryCollectionViewCell" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
-(void)updateCell {
_moduleViewController = [[VLModuleViewController alloc] initWithNibName:#"VLModuleViewController" bundle:nil];
_moduleViewController.view.frame = self.moduleSubview.bounds;
[self.moduleSubview addSubview:_moduleViewController.view];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Assets"];
NSString *filename = [NSString stringWithFormat:#"%#/%#", sourcePath, self.imageName];
UIImage *image = [UIImage imageWithContentsOfFile:filename];
NSString *fileTitle = [[filename lastPathComponent] stringByDeletingPathExtension];
[self.categoryName setFont:[UIFont fontWithName:#"OpenSans-ExtraBold" size:72.0]];
[self.categoryName setText:fileTitle];
[self.imageView setImage:image];
[self.imageView setContentMode:UIViewContentModeScaleAspectFit];
}
#end
[VLModuleViewController.h]
#import <UIKit/UIKit.h>
#interface VLModuleViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
#end
[VLModuleViewController.m]
#import "VLModuleViewController.h"
#import "VLModuleCollectionViewCell.h"
#interface VLModuleViewController ()
#property (nonatomic, strong) IBOutlet UICollectionView *moduleView;
#property (nonatomic, strong) NSArray *moduleArray;
#property (nonatomic) int currentIndex;
#property (nonatomic) NSString *cellIdentifier;
#end
#implementation VLModuleViewController
- (void)loadView {
[super loadView];
NSArray *moduleArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:#"Module_Tests"];
NSMutableArray *moduleImageArray = [[NSMutableArray alloc] initWithCapacity:[moduleArray count]];
for (NSString *path in moduleArray) {
[moduleImageArray addObject:[UIImage imageWithContentsOfFile:path]];
}
self.moduleArray = [NSArray arrayWithArray:moduleArray];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupCollectionView];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.moduleView setPagingEnabled:YES];
[self.moduleView setCollectionViewLayout:flowLayout];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark -
#pragma mark UICollectionView methods
- (void)setupCollectionView {
[self.moduleView registerClass:[VLModuleCollectionViewCell class] forCellWithReuseIdentifier:#"VLModuleCollectionViewCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.moduleView setCollectionViewLayout:flowLayout];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.moduleArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
VLModuleCollectionViewCell *cell = (VLModuleCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"VLModuleCollectionViewCell" forIndexPath:indexPath];
cell.titleLabel.text = #"Module Title Goes Here";
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(235, 147);
}
#end

I had a similar issue with labels overwriting themselves in collectionView, try calling your updateCell method in awakeFromNib, this did the trick for me.

Related

ios - horizontally scrolling collectionView with images

I am trying to show images on collectionView. I have trouble showing this images as I have created a reusable cell with imageView inside.Those images have to be equally spaced between as I want to show 3 icons on screen at once. I am using 13 icons and it has to be scrollable horizontally through screen.
I am not able to show image in cell and I do not know how to set image cells with spacing between them using just one reusable cell
CustomCollectionViewCell.h
#interface CustomCollectionViewCell : UICollectionViewCell
#property (nonatomic, retain) UIImageView *imageView;
#end
CustomCollectionViewCell.m
#implementation CustomCollectionViewCell
- (UIImageView *) imageView {
if (!_imageView) {
_imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
[self.contentView addSubview:_imageView];
}
return _imageView;
}
- (void)prepareForReuse {
[super prepareForReuse];
[self.imageView removeFromSuperview];
self.imageView = nil;
}
#end
LandingViewController.m
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
CustomCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"CustomCell" forIndexPath:indexPath];
return cell;
}
Now OP wants horizontal scrollable direction of Collection view.So Again I created small sample project for this.I put 13 images in horizontal scroll direction.It scrolls successfully on horizontal direction of collection view.
Why I post the horizontal scrollable collectionView here is everyone can understand the answer and get the solution easily.I added extra image I mean exactly 13 images(op wants 13 images into collection view). This answer definitely helps you.
HorizontalScrollableCollectionView
Here I set the scrollDirection as Horizontal in CustomImageFlowLayout.m file
CustomImageFlowLayout.h
#import <UIKit/UIKit.h>
#interface CustomImageFlowLayout : UICollectionViewFlowLayout
#end
CustomImageFlowLayout.m
#import "CustomImageFlowLayout.h"
#implementation CustomImageFlowLayout
- (instancetype)init
{
self = [super init];
if (self)
{
self.minimumLineSpacing = 1.0f;
self.minimumInteritemSpacing = 1.0f;
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}
return self;
}
- (CGSize)itemSize
{
NSInteger numberOfColumns;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
numberOfColumns = 3;
else{
if([UIApplication sharedApplication].statusBarOrientation==UIInterfaceOrientationPortrait)
numberOfColumns = 4;
else if([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeRight || [UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeLeft)
numberOfColumns = 4;
}
NSLog(#"The collection view frame is - %#",NSStringFromCGRect(self.collectionView.frame));
CGFloat itemWidth = (CGRectGetWidth(self.collectionView.frame) - (numberOfColumns - 1)) / numberOfColumns;
NSLog(#"The item width is - %f",itemWidth);
return CGSizeMake(itemWidth, itemWidth);
}
#end
Then CustomCell of UICollectionViewCell
CustomCell.xib
CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImageView *img;
#property (strong, nonatomic) IBOutlet UILabel *lblCollection;
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
#end
Now Storyboard design starts
My collection view name is here collectionviewVerticalHorizontalFlowLayout
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>
#property (strong, nonatomic) IBOutlet UICollectionView *collectionviewVerticalHorizontalFlowLayout;
#end
ViewController.m
#import "ViewController.h"
#import "CustomCell.h"
#import "CustomImageFlowLayout.h"
#interface ViewController (){
NSMutableArray *arrayImages;
NSMutableArray *arrayTitles;
CustomCell *cell;
}
#end
#implementation ViewController
#synthesize collectionviewVerticalHorizontalFlowLayout;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
collectionviewVerticalHorizontalFlowLayout.collectionViewLayout = [[CustomImageFlowLayout alloc] init];
collectionviewVerticalHorizontalFlowLayout.backgroundColor = [UIColor clearColor];
arrayImages = [[NSMutableArray alloc]initWithObjects:#"iPhone.png", #"android.png", #"windows.png", #"blackberry.png", #"lenovovibek5note.png", #"redmi.png", #"moto.png", #"sony.png", #"samsung.png", #"oneplus.png",#"redminote4.png",#"oppo.png",#"vivo.png",nil];
arrayTitles = [[NSMutableArray alloc]initWithObjects:#"iPhone", #"Android", #"Windows", #"Blackberry", #"LenovaVikeK5Note", #"Redmi", #"MotoG", #"Sony", #"Samsung", #"OnePlus", #"RedMiNote4",#"Oppo",#"Vivo",nil];
UINib *cellNib = [UINib nibWithNibName:#"CustomCell" bundle:nil];
[collectionviewVerticalHorizontalFlowLayout registerNib:cellNib forCellWithReuseIdentifier:#"cell"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//UICollectionView Data Source Methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return arrayImages.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
if(cell==nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = nib[0];
}
cell.img.image = [UIImage imageNamed:(NSString*)[arrayImages objectAtIndex:indexPath.row]];
NSLog(#"The collection view label text is - %#",[NSString stringWithFormat:#"%#",arrayTitles[indexPath.row]]);
cell.lblCollection.text = arrayTitles[indexPath.row];
cell.lblCollection.textColor = [UIColor blackColor];
return cell;
}
//UICollectionView Delegate Method
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"the clicked indexPath.row is - %ld",(long)indexPath.row);
}
#end
Final out put screen shots
First it shows
Then If I scroll horizontally in the collection view it shows
I will give you what you ask.
I wanted to same thing in one application.I successfully implemented this.Just now I tried the sample project for your question.I got what you ask exactly.I show you the code and everything below.
First CustomImageFlowLayout of NSObject Class
CustomImageFlowLayout.h
#import <UIKit/UIKit.h>
#interface CustomImageFlowLayout : UICollectionViewFlowLayout
#end
CustomImageFlowLayout.m
#import "CustomImageFlowLayout.h"
#implementation CustomImageFlowLayout
- (instancetype)init
{
self = [super init];
if (self)
{
self.minimumLineSpacing = 1.0f;
self.minimumInteritemSpacing = 1.0f;
self.scrollDirection = UICollectionViewScrollDirectionVertical;
}
return self;
}
- (CGSize)itemSize
{
NSInteger numberOfColumns;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
numberOfColumns = 3;
else{
if([UIApplication sharedApplication].statusBarOrientation==UIInterfaceOrientationPortrait)
numberOfColumns = 4;
else if([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeRight || [UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeLeft)
numberOfColumns = 4;
}
NSLog(#"The collection view frame is - %#",NSStringFromCGRect(self.collectionView.frame));
CGFloat itemWidth = (CGRectGetWidth(self.collectionView.frame) - (numberOfColumns - 1)) / numberOfColumns;
NSLog(#"The item width is - %f",itemWidth);
return CGSizeMake(itemWidth, itemWidth);
}
#end
After that I created Custom Cell for Images
See my Design first
CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImageView *img;
#property (strong, nonatomic) IBOutlet UILabel *lblCollection;
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#end
Then I use above class in my ViewController
Below is my Storyboard Design
Here my CollectionView name is collectionViewVertical
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
#property (strong, nonatomic) IBOutlet UICollectionView *collectionViewVertical;
#end
ViewController.m
#import "ViewController.h"
#import "CustomCell.h"
#import "CustomImageFlowLayout.h"
#interface ViewController ()
{
NSMutableArray *arrayImages;
NSMutableArray *arrayTitles;
CustomCell *cell;
}
#end
#implementation ViewController
#synthesize collectionViewVertical;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
collectionViewVertical.collectionViewLayout = [[CustomImageFlowLayout alloc] init];
collectionViewVertical.backgroundColor = [UIColor clearColor];
arrayImages = [[NSMutableArray alloc]initWithObjects:#"iPhone", #"Android", #"Windows", #"Blackberry", #"Lenova", #"Redmi", #"MotoG", #"Sony", #"Samsung", #"OnePlus", nil];
arrayTitles = [[NSMutableArray alloc]initWithObjects:#"iPhone.png", #"android.png", #"windows.png", #"blackberry.png", #"lenovo.png", #"redmi.png", #"moto.png", #"sony.png", #"samsung.png", #"oneplus.png", nil];
UINib *cellNib = [UINib nibWithNibName:#"CustomCell" bundle:nil];
[collectionViewVertical registerNib:cellNib forCellWithReuseIdentifier:#"cell"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//UICollectionView Data Source Methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return arrayImages.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
if(cell==nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = nib[0];
}
cell.img.image = [UIImage imageNamed:(NSString*)[arrayImages objectAtIndex:indexPath.row]];
cell.lblCollection.text = arrayTitles[indexPath.row];
return cell;
}
//UICollectionView Delegate Method
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"the clicked indexPath.row is - %ld",(long)indexPath.row);
}
Finally the output screen

UICollectionView Crashes when Cell is Touched

I have a UICollectionView with a custom class subclassed to UICollectionViewCell showing pictures from within the app. It loads fine, but if any cell is even barely touched, the app crashes. There is no error message in the Console, and nothing shows if I put in an Exception breakpoint either. The code for the view controller containing the Collection View is:
#import "ImagePicker.h"
#import "CMFGalleryCell.h"
#interface ImagePicker ()
#property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
#property (nonatomic, strong) NSArray *dataArray;
#end
#implementation ImagePicker
#synthesize dataArray, collectionView;
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Choose Image";
[self loadImages];
[self setupCollectionView];
// Do any additional setup after loading the view from its nib.
}
-(void)setupCollectionView {
[self.collectionView registerClass:[CMFGalleryCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[flowLayout setMinimumInteritemSpacing:0.0f];
[flowLayout setMinimumLineSpacing:0.0f];
[self.collectionView setPagingEnabled:YES];
[self.collectionView setCollectionViewLayout:flowLayout];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.dataArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CMFGalleryCell *cell = (CMFGalleryCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSString *imageName = [self.dataArray objectAtIndex:indexPath.row];
[cell setImageName:imageName];
[cell updateCell];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Chose%ld", (long)indexPath.row);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(185, 185);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 1.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 1.0;
}
// Layout: Set Edges
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
// return UIEdgeInsetsMake(0,8,0,8); // top, left, bottom, right
return UIEdgeInsetsMake(0,0,0,0); // top, left, bottom, right
}
-(void)loadImages {
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"inviteimages"];
self.dataArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:NULL];
NSLog(#"%#", self.dataArray);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
The custom Cell is:
#import "CMFGalleryCell.h"
#interface CMFGalleryCell()
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#end
#implementation CMFGalleryCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"CMFGalleryCell" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
-(void)updateCell {
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"inviteimages"];
NSString *filename = [NSString stringWithFormat:#"%#/%#", sourcePath, self.imageName];
UIImage *image = [UIImage imageWithContentsOfFile:filename];
[self.imageView setImage:image];
[self.imageView setContentMode:UIViewContentModeScaleAspectFill];
}
#end
What is going on causing it to crash if a cell is touched? If I touch the space between cells, I can get it to scroll, but any touch at all of the cell crashes.
Screenshot of crash without zombies:
Screenshot of crash with zombies:
You said you app will crash when cell is touched but you haven't implemented the cell select delegate method but written only cell deselect delegate method. Try this
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
And insert a breakpoint inside the same method to debug. If break point is not called then something else is the problem
Maybe problem is in your View Controller class:
#property link to ImagePicker can be weak, and you, for example, remove it from superview. After this, ImagePicker object will be deallocated.
Try to replace
#property (weak, nonatomic) ImagePicker *someImagePicker
with
#property (strong, nonatomic) ImagePicker *someImagePicker
Can you share code from your UIViewController?

Programatically creating the custom UICollectionViewCell and setting the properties

I've been trying to configure a custom UICollectionViewCell that is supposed to present a UIView consisting of a few subviews generated with a custom method.
The problem is that when I try to pass the needed data from -cellForItemAtIndexPath to the cell's properties (NSStrings) the app crashes and the data doesn't seem to be passed at all, because NSLog returns (null) for all of the properties.
I thought that the problem was with the properties not being initialized, but when I initialized them in -initWithFrame, they didn't return any values. I tried to use the -initWithCoder and -awakeFromNib and it didn't work.
I also tried to utilize a custom method that would set the properties for me. While it seems to be working, I can't seem to find a way to add the generated view to the cell's view, as using [self.contentView addSubview:...] seems to be adding every generated view to every cell in the Collection View.
If you guys could help me out, I would be much grateful - I've spent my entire day on this, and I just can't get it to work. Perhaps I should do it differently?
My custom collection view cell's .h file:
#import "SHDesignChicago.h"
#interface SHDesignChicagoCollectionViewCell : UICollectionViewCell
#property (strong, nonatomic) NSString *name;
#property (strong, nonatomic) NSString *date;
#property (strong, nonatomic) NSString *going;
#property (strong, nonatomic) PFFile *background;
#property (strong, nonatomic) UIView *generatedDesign;
- (void)setCellWithEventName:(NSString *)name eventDate:(NSString *)date eventGoing:(NSString *)going eventBackground:(PFFile *)background;
#end
And my custom collection view cell's .m file:
#import "SHDesignChicagoCollectionViewCell.h"
#implementation SHDesignChicagoCollectionViewCell
- (void)setCellWithEventName:(NSString *)name eventDate:(NSString *)date eventGoing:(NSString *)going eventBackground:(PFFile *)background {
UIImage *backgroundImage = [[UIImage alloc] initWithData:[background getData]];
NSLog(#"Event details:\nName: %#\nDate: %#\nGoing: %#\nBackground: %#", name, date, going, background);
self.generatedDesign = [SHDesignChicago designWithName:name date:date going:going background:backgroundImage frame:self.frame];
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//self.autoresizesSubviews = YES;
__block UIImage *backgroundImage;
[self.background getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) backgroundImage = [[UIImage alloc] initWithData:data];
}];
NSLog(#"Event details:\nName: %#\nDate: %#\nGoing: %#\nBackground: %#", self.name, self.date, self.going, self.background);
if (self.name != nil) {
UIView *generatedDesign = [SHDesignChicago designWithName:self.name date:self.date going:self.going background:backgroundImage frame:self.frame];
[self addSubview:generatedDesign];
}
}
return self;
}
#end
Also the cellForItemAtIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PFObject *event = [self.events objectAtIndex:indexPath.row];
NSString *name = event[#"eventName"];
NSDate *date = event[#"eventDate"];
PFFile *background = event[#"coverPhoto"];
if ([event[#"designId"] isEqual: #(1)]) {
// SHDesignChicago
SHDesignChicagoCollectionViewCell *chicagoCell = (SHDesignChicagoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"chicago" forIndexPath:indexPath];
/*
chicagoCell.name = #"TEST";
chicagoCell.date = #"TODAY, 5 PM";
chicagoCell.going = #"NATALIA KAWECKA AND 35 OTHERS ARE GOING";
chicagoCell.background = background;
*/
[chicagoCell setCellWithEventName:name eventDate:#"TODAY, 5 PM" eventGoing:#"NATALIA M AND 35 OTHERS ARE GOING" eventBackground:background];
return chicagoCell;
}
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
return cell;
}

button in cell with weblink

I am trying to add a simple button to a custom cell that has a web link. I added the button in story board and associated it with houseLink. Here is my view.M file where I call the button from the custom cell.
#import "IBSecondViewController.h"
#import "C21TableCell.h"
#interface IBSecondViewController ()
#end
#implementation IBSecondViewController
{
NSArray *thumbnails;
}
#synthesize data;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Initialize House Array
data = [NSArray arrayWithObjects:#"2109 E Avon Cricle, Hayden Lake, ID", #"703 E Garden, Coeur d' Alene, ID", nil];
_bedroom = [NSArray arrayWithObjects:#"3", #"4", nil];
// Initialize thumbnails
thumbnails = [NSArray arrayWithObjects:#"stockHouse.png", #"stockHouse2.png", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view ddata source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"C21TableCell";
C21TableCell *cell = (C21TableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"C21TableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.addressLabel.text = [data objectAtIndex:indexPath.row];
cell.bedroomLabel.text = [_bedroom objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
NOT SURE HOW TO CALL THE BUTTON HERE
return cell;
}
-(void) buttonpressed:(UIButton *)sender {
NSString* launchUrl = #"http://apple.com/";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}
#end
C21TableCell.H
#import <UIKit/UIKit.h>
#interface C21TableCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *addressLabel;
#property (nonatomic, weak) IBOutlet UILabel *bedroomLabel;
#property (nonatomic, weak) IBOutlet UIImageView *thumbnailImageView;
#property (nonatomic, weak) IBOutlet UIButton *homeLink;
#end
C21TableCell.M
#import "C21TableCell.h"
#implementation C21TableCell
#synthesize addressLabel = _nameLabel;
#synthesize bedroomLabel = _bedroomLabel;
#synthesize thumbnailImageView = _thumbnailImageView;
#synthesize homeLink = homeLink;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)awakeFromNib
{
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
Just add target to button action when you create cell
[cell.homeLink addTarget:self action:#selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];

Set label for a custom cell

I have a custom table cell and I'm just trying to set the label, image, etc but for some reason it's not working.
Here is my code for my custom cell
BrowserMenuCell.h
#import <UIKit/UIKit.h>
#interface BrowseMenuCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UIButton *wishListBUtton;
#property (strong, nonatomic) IBOutlet UIImageView *itemImage;
#property (strong, nonatomic) IBOutlet UILabel *itemLabel;
#property (strong, nonatomic) IBOutlet UILabel *itemPrice;
#property (strong, nonatomic) IBOutlet UITextField *quantityField;
#property (strong, nonatomic) IBOutlet UILabel *totalLabel;
- (IBAction)plusButton:(id)sender;
- (IBAction)cartButton:(id)sender;
- (IBAction)minusButton:(id)sender;
#end
BrowserMenuCell.m
#import "BrowseMenuCell.h"
#implementation BrowseMenuCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (IBAction)plusButton:(id)sender {
}
- (IBAction)cartButton:(id)sender {
}
- (IBAction)minusButton:(id)sender {
}
#end
Cell for row at index path
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BrowseMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
OfficeSupply *supply = [_items objectAtIndex:indexPath.row];
if(cell == nil)
{
NSArray * views = [[NSBundle mainBundle] loadNibNamed:#"BrowseMenuCell" owner:nil options:nil];
for (id obj in views){
if([obj isKindOfClass:[UITableViewCell class]])
{
BrowseMenuCell * obj = [[BrowseMenuCell alloc]init];
obj.itemLabel.text = supply.itemName;
cell = obj;
break;
}
}
}
return cell;
}
Have you tried using [self.tableView reloadData]?
To start with, don't create a new random instance of the cell after you have already created one from the NIB file. Change the code to this:
for (BrowseMenuCell *obj in views){
if([obj isKindOfClass:[BrowseMenuCell class]])
{
obj.reuseIdentifier = #"ItemsCell";
obj.itemLabel.text = supply.itemName;
cell = obj;
break;
}
}
That won't guarantee it works, but at least the NIB setup of your labels won't be getting thrown away.
If it still doesn't work. Debug. Check the frames of the labels. Check the label references are set (not nil).
This is the wrong way you create cell. Try this one:
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BrowseMenuCell *cell = (BrowseMenuCell*)[tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
OfficeSupply *supply = [_items objectAtIndex:indexPath.row];
if (_cellObj == nil) {
[[NSBundle mainBundle] loadNibNamed:#"BrowseMenuCell" owner:nil options:nil];
}
cell.itemlabel.text = supply.itemName;
return cell;
}

Resources