Nothing apear in UIcollectionView Controller - ios

I have UIcollectionView in my first view of application after Uinavigationviewcontroller just in storyboard just like this :
this is my RootViewController.h
#import <UIKit/UIKit.h>
#interface RootViewController : UICollectionViewController<UICollectionViewDelegate,UICollectionViewDataSource>
#property (nonatomic, strong) NSArray *entries;
#end
and my RootViewController.m :
#import "RootViewController.h"
#import "AppRecord.h"
#import "Cell.h"
#define kCustomRowCount 7
#interface RootViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
// the set of IconDownloader objects for each app
#property (nonatomic, strong) NSMutableDictionary *imageDownloadsInProgress;
#end
#implementation RootViewController
#pragma mark
// -------------------------------------------------------------------------------
// viewDidLoad
// -------------------------------------------------------------------------------
- (void)viewDidLoad
{
NSLog(#"inside class");
[super viewDidLoad];
// self.title = #"My Title";
//self.collectionView.delegate = self;
//self.collectionView.dataSource=self;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSUInteger count = [self.entries count];
NSLog(#"count: %lu", (unsigned long)count);
if (count == 0)
{
return kCustomRowCount;
}
return count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"inside cell");
AppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"MY_CELL" forIndexPath:indexPath];
UIImage *truckImage = [[UIImage alloc] init];
truckImage = [UIImage imageNamed:#"Default.png"];
cell.imageView.image = truckImage;
return cell;
}
#end
now problem is none of my "cellForItemAtIndexPath" or "numberOfItemsInSection" or even "viewDidLoad" getting called and the output on Simulator is black screen.
This is my reload section of AppDelegate class :
__block ParseOperation *weakParser = parser;
parser.completionBlock = ^(void) {
if (weakParser.appRecordList) {
dispatch_async(dispatch_get_main_queue(), ^{
RootViewController *rootViewController = (RootViewController*)[(UINavigationController*)self.window.rootViewController topViewController];
rootViewController.entries = weakParser.appRecordList;
if(weakParser.appRecordList != nil)
NSLog(#"weakParser.appRecordList is Not nill");
[rootViewController.collectionView reloadItemsAtIndexPaths:[rootViewController.collectionView indexPathsForVisibleItems]];
[rootViewController.collectionView reloadData];
});
}
self.queue = nil;
};
[self.queue addOperation:parser];
self.appListData = nil;
}

Did you add the delegate and datasource connection for the collection view? It's the most common mistake, usually. They're commented out in code, I assume you did that via Storyboard

Do you have identifier on the storyboard cell?You can try to add
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"MY_CELL"];
in viewDidLoad
Since your RootViewController inherit UICollectionViewController you don't need to add UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout at all

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

memory issue nsobject and nsmutablearray UICollectionView

I added a simple collection view and i add items fetched from my backend , when I add all the objects to a nsmutablearray it takes less memory but when I add the fetched objects to a NSObject while scrolling the collection view it takes more memory .
here is a sample code
myObjectModel.h
#import <Foundation/Foundation.h>
#interface myObjectModel: NSObject
#property (nonatomic, strong) NSString *objectTitle;
#property (nonatomic, strong) NSString *objectDesc;
#property (nonatomic, strong) NSString *objectImgURL;
- (id)initWithObjectTitle:(NSString *)dTitle
objectImgURL:(NSString *)dObjectImgURL
objectDesc:(NSString *)dObjectDesc;
#end
myObjectModel.m
#import "myObjectModel.h"
#implementation myObjectModel
- (id)initWithObjectTitle:(NSString *)dTitle
objectImgURL:(NSString *)dObjectImgURL
objectDesc:(NSString *)dObjectDesc {
self = [super init];
if (self) {
self.objectTitle = dTitle;
self.objectImgURL = dObjectImgURL;
self.objectDesc = dObjectDesc;
}
return self;
}
#end;
then I imported this header to my UIViewController which has a collectionview while fetching all the objects i add this method to add those objects and then save them into a nsmutablearray
BackendlessDataQuery *query = [BackendlessDataQuery query];
query.queryOptions.pageSize = #(100); //set page size
[[backendless.persistenceService of:[Channels class]] find:query response:^(BackendlessCollection *backendlessObjects) {
NSArray *currentPage = [backendlessObjects getCurrentPage];
NSMutableArray *arrData = [[NSMutableArray alloc]init];
for (Objects *objects in currentPage) {
#autoreleasepool {
myObjectModel *dataItem = [[myObjectModel alloc]initWithObjectTitle:backendlessObjects.title
objectImgURL:backendlessObjects.image
objectDesc:backendlessObjects.Desc;
[arrData addObject:dataItem];
}
//Test is a nsarray added in the header file
self.test = arrData;
[self.collectionView reloadData];
} error:^(Fault *fault) {
}];
here is what I add to my collection data source
#pragma mark - UICollectionViewDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView; {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [test count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
myCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"data" forIndexPath:indexPath];
myObjectModel *dataItem = (myObjectModel*)[test objectAtIndex:indexPath.row];
// cell.objectTitle.text = dataItem.objectTitle;
[cell.channelImg sd_setImageWithURL:[NSURL URLWithString:dataItem.objectImgURL] placeholderImage:[UIImage imageNamed:#"NoImage.png"]];
return cell;
}
when I run this code all my objects will appear in the collectionview but while scrolling the memory keeps increasing.
There is no reason to increase memory by using test Array the reason is by using this
[cell.channelImg sd_setImageWithURL:[NSURL URLWithString:dataItem.objectImgURL] placeholderImage:[UIImage imageNamed:#"NoImage.png"]];
this will Asynchronously download image from URL.if you comment above line then it may not increase memory.

UiCollcetionViewCell specific segue to connect TableView show specific content within TableView

Hi there the question i would like to ask is there a way of creating such code in Objective C that will allow me to select a single UICollectionViewCell within a UICollectionViewController and link it to a table view that shows UICollectionViewCell specific content based upon what UICollectionViewCell has been selected without creating hundreds of UITableViewControllers?
A know this is not code but this is what i want the code to achieve if it is possible:
on click of collection view cell dresses show table view.
then on the table view...
if collection view clicked was dresses display dresses table view.
surely this is possible?
Also if possible i would like the code to somehow group things togethers as this will be done on a large scale i have 106 collection view cells that need linking to table views of which need to contain a minimum of 30 TableViewCells each.
I tried your question for getting solution.Finally I successfully got the solution.Below code works perfectly.
In ViewController
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
#property (strong, nonatomic) IBOutlet UICollectionView *collectionViewSelection;
#end
.m
#import "ViewController.h"
#import "CustomCollectionViewCell.h"
#import "DetailViewController.h"
#interface ViewController ()
{
NSMutableArray *arrayCollectionView;
NSMutableArray *imgArray;
NSMutableArray *lblArray;
}
#end
#implementation ViewController
#synthesize collectionViewSelection;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
imgArray = [NSMutableArray arrayWithObjects:
[UIImage imageNamed:#"casual.png"],
[UIImage imageNamed:#"checked.png"],
[UIImage imageNamed:#"collar.png"],
[UIImage imageNamed:#"formal.png"],
[UIImage imageNamed:#"jean.png"],
[UIImage imageNamed:#"neck.png"],
[UIImage imageNamed:#"pant.png"],nil];
lblArray = [NSMutableArray arrayWithObjects:#"casual",#"checked",#"collar",#"formal",#"jean",#"neck",#"pant", nil];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
UINib *cellNib = [UINib nibWithNibName:#"CustomCollectionViewCell" bundle:nil];
[collectionViewSelection registerNib:cellNib forCellWithReuseIdentifier:#"customCollectionCell"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [lblArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"customCollectionCell";
CustomCollectionViewCell *cell = (CustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSLog(#"The current indexPath row is - %ld",(long)indexPath.row);
cell.img_Collection.image = [imgArray objectAtIndex:indexPath.row];
cell.label_Collection.text = [lblArray objectAtIndex:indexPath.row];
cell.tag = indexPath.row;
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(260, 176);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"The touched index path os collection cell item row is - %ld",(long)indexPath.row);
DetailViewController *detailsVC = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
detailsVC.stringLabeldata = [lblArray objectAtIndex:indexPath.row];
detailsVC.imageData = [imgArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailsVC animated:YES];
}
#end
DetailViewController
.h
#import <UIKit/UIKit.h>
#interface DetailViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tableViewDressesData;
#property (strong, nonatomic) UIImage *imageData;
#property (strong, nonatomic) NSString *stringLabeldata;
- (IBAction)actionBack:(id)sender;
#end
.m
#import "DetailViewController.h"
#import "CustomTableViewCell.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
#synthesize tableViewDressesData;
#synthesize imageData,stringLabeldata;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSLog(#"The labeldata is -%#",stringLabeldata);
[tableViewDressesData registerNib:[UINib nibWithNibName:#"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:#"cell"];
[tableViewDressesData reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.imgViewDetail.image = imageData;
cell.labelDetail.text = stringLabeldata;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 188;
}
- (IBAction)actionBack:(id)sender
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
#end

Populating 2 collection views from two arrays of images

so I've been searching around and although there are many threads explaining close to what I need, I still can't successfully execute my code. I have two collection views on my ViewController, one with 6 cells running across, and another with 32 cells (4 top to bottom, 8 across). Each collection view needs to be populated from an array of 3 images, they're the same images, just different colors and I'd like to have them randomly populated. I have two cell.xib files, one for each collection view. Below is the .m file for the ViewController I'm working with.
#import "FirstViewController.h"
#import "CollectionViewCell.h"
#import "RemotesCollectionCell.h"
#import <stdlib.h>
#interface FirstViewController ()
#end
#implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UINib *cellNib = [UINib nibWithNibName:#"CollectionViewCell" bundle:nil];
[self.headerViewCollection registerNib:cellNib forCellWithReuseIdentifier:#"collectCell"];
UINib *cellNibRemote = [UINib nibWithNibName:#"RemotesCollectionCell" bundle:nil];
[self.remoteViewCollection registerNib:cellNibRemote forCellWithReuseIdentifier:#"collectCell"];
self.headLabel.text=[NSString stringWithFormat:#"H\nE\nA\nD"];
self.remotesLabel.text = [NSString stringWithFormat:#"R\nE\nM\nO\nT\nE\nS"];
self.title = [NSString stringWithFormat:#"OTIS"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
};
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
if(collectionView == self.headerViewCollection){
return 6;
}
else return 32;
};
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"collectCell" forIndexPath:indexPath];
return cell;
};
#end
Here is my .h file for one of the cell.xib files
#import <UIKit/UIKit.h>
#interface RemotesCollectionCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImageView *remoteImageView;
#end
And here is the .m file for the nib.
#import "RemotesCollectionCell.h"
#import "FirstViewController.h"
#implementation RemotesCollectionCell
- (void)awakeFromNib {
// Initialization code
NSMutableArray *remoteImages = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:#"red-gps.png"], [UIImage imageNamed:#"green-gps.png"], [UIImage imageNamed:#"orange-gps.png"], nil];
_remoteImageView = [[UIImageView alloc]initWithFrame:self.contentView.bounds];
[self.contentView addSubview:_remoteImageView];
NSLog(#"%lu", (unsigned long)remoteImages.count);
}
#end
I apologize for all the code but I hope it'll help you help me, thank you in advance. Please forgive my noob showing.
//In awakeFromNib method define with _remoteImageView.tag=1; so that you can access in cellForIndexPath
- (void)awakeFromNib {
// Initialization code
NSMutableArray *remoteImages = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:#"red-gps.png"], [UIImage imageNamed:#"green-gps.png"], [UIImage imageNamed:#"orange-gps.png"], nil];
_remoteImageView = [[UIImageView alloc]initWithFrame:self.contentView.bounds];
_remoteImageView.tag=1;
[self.contentView addSubview:_remoteImageView];
NSLog(#"%lu", (unsigned long)remoteImages.count);
}
//Here whenever the cells are loading load the images after randomizing the array.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"collectCell" forIndexPath:indexPath];
NSMutableArray *remoteImages = [[NSMutableArray alloc]initWithObjects:#"red-gps.png", #"green-gps.png", #"orange-gps.png", nil];
int count = (int)[remoteImages count];
for (int i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[remoteImages exchangeObjectAtIndex:i withObjectAtIndex:n];
}
NSLog(#"remoteImages=%#",remoteImages);
UIImageView *imageView = (UIImageView*)[cell.contentView viewWithTag:1];
imageView.image=[UIImage imageNamed:[remoteImages objectAtIndex:0]];
return cell;
};

popovercontroller tableview controller cell null

in the begining iOS 5 Development exploring the iOS sdk chapter 11 "iPad Considerations",the "Creating Your Own Popover" paragraph,i try it my self,but just give an error output "Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'"
codes as follows:(because I am first ask question on the stackoverflow website and my english is poor ,so just forgive my fault on the expression)
1.PrLanguageListController.h
#import <UIKit/UIKit.h>
#class PrDetailViewController;
#interface PrLanguageListController : UITableViewController
#property (weak, nonatomic) PrDetailViewController *detailViewController;
#property (strong, nonatomic) NSArray *languageNames;
#property (strong, nonatomic) NSArray *languageCodes;
#end
2.PrLanguageListContrller.m
#import "PrLanguageListController.h"
#import "PrDetailViewController.h"
#interface PrLanguageListController ()
#end
#implementation PrLanguageListController
#synthesize detailViewController;
#synthesize languageCodes;
#synthesize languageNames;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.languageNames = [NSArray arrayWithObjects:#"English", #"French",
#"German", #"Spanish", nil];
self.languageCodes = [NSArray arrayWithObjects:#"en", #"fr", #"de", #"es", nil];
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0,
[self.languageCodes count] * 44.0);
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.detailViewController = nil;
self.languageNames = nil;
self.languageCodes = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.languageCodes count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
cell.textLabel.text = [languageNames objectAtIndex:[indexPath row]];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
detailViewController.languageString = [self.languageCodes objectAtIndex:
[indexPath row]];
}
#end
3.PrDetailViewController.h
#import <UIKit/UIKit.h>
#interface PrDetailViewController : UIViewController <UISplitViewControllerDelegate>
#property (strong, nonatomic) id detailItem;
#property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#property (weak, nonatomic) IBOutlet UIWebView *webView;
#property (strong, nonatomic) UIBarButtonItem *languageButton;
#property (strong, nonatomic) UIPopoverController *languagePopoverController;
#property (copy, nonatomic) NSString *languageString;
- (IBAction)touchLanguageButton;
#end
4.PrDetailViewController.m
#import "PrDetailViewController.h"
#import "PrLanguageListController.h"
#interface PrDetailViewController ()
#property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
#end
#implementation PrDetailViewController
#synthesize detailItem = _detailItem;
#synthesize detailDescriptionLabel = _detailDescriptionLabel;
#synthesize masterPopoverController = _masterPopoverController;
#synthesize webView;
#synthesize languageButton;
#synthesize languagePopoverController;
#synthesize languageString;
#pragma mark - Managing the detail item
//rewrite url for different languages.eg.www.wekipak.com/us--ch...etc
static NSString * modifyUrlForLanguage(NSString *url, NSString *lang) {
if (!lang) {
return url;
}
// We're relying on a particular Wikipedia URL format here. This
// is a bit fragile!
NSRange languageCodeRange = NSMakeRange(7, 2);
if ([[url substringWithRange:languageCodeRange] isEqualToString:lang]) {
return url;
} else {
NSString *newUrl = [url stringByReplacingCharactersInRange:languageCodeRange
withString:lang];
return newUrl;
}
}
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
//_detailItem = newDetailItem;
_detailItem = modifyUrlForLanguage(newDetailItem, languageString);
// Update the view.
[self configureView];
}
if (self.masterPopoverController != nil) {
[self.masterPopoverController dismissPopoverAnimated:YES];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
NSURL *url = [NSURL URLWithString:self.detailItem];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem description];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.languageButton = [[UIBarButtonItem alloc] init];
languageButton.title = #"Choose Language";
languageButton.target = self;
languageButton.action = #selector(touchLanguageButton);
self.navigationItem.rightBarButtonItem = self.languageButton;
[self configureView];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.detailDescriptionLabel = nil;
self.webView = nil;
self.languageButton = nil;
self.languagePopoverController = nil;
}
- (void)setLanguageString:(NSString *)newString {
if (![newString isEqualToString:languageString]) {
languageString = [newString copy];
self.detailItem = modifyUrlForLanguage(_detailItem, languageString);
}
if (languagePopoverController != nil) {
[languagePopoverController dismissPopoverAnimated:YES];
self.languagePopoverController = nil;
}
}
- (IBAction)touchLanguageButton {
if (self.languagePopoverController == nil) {
PrLanguageListController *languageListController =
[[PrLanguageListController alloc] init];
languageListController.detailViewController = self;
UIPopoverController *poc = [[UIPopoverController alloc]
initWithContentViewController:languageListController];
[poc presentPopoverFromBarButtonItem:languageButton
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
self.languagePopoverController = poc;
} else {
if (languagePopoverController != nil) {
[languagePopoverController dismissPopoverAnimated:YES];
self.languagePopoverController = nil;
}
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#pragma mark - Split view
- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
barButtonItem.title = NSLocalizedString(#"Presidents", #"Presidents");
//barButtonItem.title = NSLocalizedString(#"Master", #"Master");
[self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
self.masterPopoverController = popoverController;
}
- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
// Called when the view is shown again in the split view, invalidating the button and popover controller.
[self.navigationItem setLeftBarButtonItem:nil animated:YES];
self.masterPopoverController = nil;
}
#end
when choose the change the language tap button it running down,and give the terminal exception...
output:
2012-05-27 19:20:37.803 Presidents[4864:f803] * Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:6061
2012-05-27 19:20:37.804 Presidents[4864:f803] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
** First throw call stack:
(0x13ce022 0x155fcd6 0x1376a48 0x9af2cb 0xb2d28 0xb33ce 0x9ecbd 0xad6f1 0x56d21 0x13cfe42 0x1d86679 0x1d90579 0x1d90674 0x50967 0x4b84e9 0x4b9548 0x3ee9 0x13cfe99 0x1b14e 0x259a0e 0x13cfe99 0x1b14e 0x1b0e6 0xc1ade 0xc1fa7 0xc1266 0x403c0 0x405e6 0x26dc4 0x1a634 0x12b8ef5 0x13a2195 0x1306ff2 0x13058da 0x1304d84 0x1304c9b 0x12b77d8 0x12b788a 0x18626 0x23dd 0x2345 0x1)
terminate called throwing an exception(lldb)
How could i solve this problem ? thanksgiving ...
You need to add alloc/init of your cell in PrLanguageListContrller.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
add this
**if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];**
...
cell.textLabel.text = [languageNames objectAtIndex:[indexPath row]];
return cell;
}

Resources