UICollectionView not showing images from CameraImage - Objective C - objective-c

Searched the forum and could not find a suitable answer that works. I suspect something is wrong with the code. I am taking pictures with a camera and trying to show them in a UICollectionView. The collectionView has a cell with a UIImageView inside of it.
Even when setting a static image and background colour I still don't see anything (not even the colour).
Code is as follows:
#import "CameraPageViewController.h"
#interface CameraPageViewController ()
#end
#implementation CameraPageViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_imageList = [[NSMutableArray alloc] init];
_collectionView.delegate = self;
_collectionView.dataSource = self;
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"PictureCell"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)takePhoto:(id)sender {
UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
imagePickController.sourceType=UIImagePickerControllerSourceTypeCamera;
imagePickController.delegate=self;
imagePickController.allowsEditing=TRUE;
[self presentViewController:imagePickController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
UIImage *chosenImage = editingInfo[UIImagePickerControllerOriginalImage];
[_imageList addObject:chosenImage];
[self dismissViewControllerAnimated:YES completion:nil];
[_collectionView reloadData];
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.imageList count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"PictureCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *pictureView = (UIImageView *) [cell viewWithTag:110];
NSInteger rowValue = indexPath.row;
UIImage *currentImage = [_imageList objectAtIndex:indexPath.row];
pictureView.image = currentImage;
return cell;
}
#end

i think u might missed the setting the layout for your collection view set it and try
- (void)viewDidLoad
{
[super viewDidLoad];
//...other code
_imageList = [[NSMutableArray alloc] init];
//set layout hear
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; //default layout
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
flowLayout.minimumInteritemSpacing = 0.0f;
flowLayout.minimumLineSpacing = 0.33f; //set the offset between items
_collectionView.showsHorizontalScrollIndicator = NO;
_collectionView.showsVerticalScrollIndicator = NO;
[_collectionView setCollectionViewLayout:flowLayout];
_collectionView.delegate = self;
_collectionView.dataSource = self;
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"PictureCell"];
}
//implement this delegate method to return item size for each cell
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(200.0f,300.0f);
}

Fixed it by adding the images as sub views through the code instead of the story board. No idea why it works, but it did.

Related

Objective C Passing CGFloat value between two classes

I have a small problem ..
For convenience and to make you understand better how to share the collection View:
Collectionview 1 has the customized segment control function (it has a custom UICollectionView custom class)
Collectionview 2 contains the cells that function as pages (it has a UICollectionViewController class).
I have an UIViewController that contains the collectionview1 that I used to create a custom segment control (like a menu)
The cursor indicating which cell was selected was created with a uiview in the collectionView 1 class.
In my main view controller in addition to having a collectionview I also inserted a container view that contains a collectionview controller that will be used to show the selected pages through a horizontal scroll.
My problem now appears when I want to pass the ContentOffset value into the collectionView2 scrollViewDidScroll to the cursor in the collectionView 1.
I tried to initialize the collectionview 1 class in the collectionView 2 class to use the cursor directly but I do not get any results.
Can you help me understand how to solve this problem?
This is Class CollectionView 1 ( Menu )
-(instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setupControl];
}
return self;
}
-(void)setupControl {
self.delegate = self;
self.dataSource = self;
self.pagingEnabled = YES;
self.showsHorizontalScrollIndicator = NO;
UINib *nib = [UINib nibWithNibName:#"UDSectionNavCell" bundle: nil];
[self registerNib:nib forCellWithReuseIdentifier:#"SCC"];
[self layout];
_horizontalCursorBar = [[UDSectionNavCursor alloc] init];
_horizontalCursorBar.frame = CGRectMake(0, self.frame.size.height - 6, self.frame.size.width / 4, 3);
_horizontalCursorBar.layer.cornerRadius = 3;
_horizontalCursorBar.backgroundColor = [UIColor colorWithHexString:#"#C1C1C1" setAlpha:1];
_horizontalCursorBar.alpha = 1;
[self addSubview:_horizontalCursorBar];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
[self selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
}
-(void)layout {
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
layout.itemSize = CGSizeMake(self.frame.size.width / 4, self.frame.size.height);
layout.minimumInteritemSpacing = 10;
layout.minimumLineSpacing = 0;
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.collectionViewLayout = layout;
[self reloadData];
}
-(NSArray *)dataPage {
return [NSArray arrayWithObjects:#"ATENEO",#"STATISTICHE",#"CALENDARIO",#"NOTIFICHE", nil];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self dataPage].count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
static NSString *cellID = #"SCC";
UDSectionNavCell *cell = (UDSectionNavCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
cell.titlePage.text = [[self dataPage] objectAtIndex:indexPath.item];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:indexPath.row inSection:0];
[self scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
if (indexPath == newIndexPath) {
[self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
[UIView animateWithDuration:.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseOut animations:^{
CGFloat x = (indexPath.item) * self.frame.size.width / 4;
_horizontalCursorBar.frame = CGRectMake(x, self.frame.size.height - 6, self.frame.size.width / 4, 3);
} completion:nil];
}
This is the code of CollectionView 2 (page cell)
static NSString * const reuseIdentifier = #"Cell";
- (void)viewDidLoad {
[super viewDidLoad];
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
UICollectionViewFlowLayout *collectionLayout = [[UICollectionViewFlowLayout alloc] init];
collectionLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
collectionLayout.minimumLineSpacing = 0;
self.collectionView.collectionViewLayout = collectionLayout;
[self.collectionView reloadData];
self.collectionView.pagingEnabled = YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 4;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
NSArray *array = [NSArray arrayWithObjects:[UIColor redColor],[UIColor blueColor], [UIColor clearColor], [UIColor grayColor], nil];
cell.backgroundColor = array[indexPath.item];
return cell;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSLog(#"%f",scrollView.contentOffset.x / 4);
}
I would need to pass the ContentOffset value of the scrollViewDidScroll method in the collectionView 2 class and use it in the collectionView class 1

NSCollectionViewItems don't reload when scrolling <OSX - Objective C>

I'm new to learning Objective-C and I have a problem with NSCollectionView which I couldn't find any ways to resolve it.
My problem is:
I wrote a button event to create a NSCollectionView named thoughtCollectionView and added onto my contentView to display NSCollectionViewItems.
When I run the simulator, items look okay, but they don't reload when I scroll.
Here's my code:
MainViewController.m
- (void)thoughtShow{
// Add Collection View
thoughtCollectionView = [[ThoughtCollection alloc] initWithFrame:NSMakeRect(0, 0, contentWidth, contentHeight)];
NSCollectionViewFlowLayout *layout = [[NSCollectionViewFlowLayout alloc] init];
[thoughtCollectionView setCollectionViewLayout:layout];
[layout setScrollDirection:NSCollectionViewScrollDirectionVertical];
layout.itemSize = NSMakeSize(50, 50);
layout.minimumInteritemSpacing = 20;
layout.sectionInset = NSEdgeInsetsMake(20, 20, 20, 20);
[thoughtCollectionView registerClass:ThoughtItems.self forItemWithIdentifier:#"ThoughtItems"];
thoughtScrollView = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, contentWidth, contentHeight)];
thoughtScrollView.documentView = thoughtCollectionView;
[contentView addSubview:thoughtScrollView];
[thoughtCollectionView reloadData];
[thoughtCollectionView setNeedsDisplay:YES];
[thoughtCollectionView layoutSubtreeIfNeeded];
}
MainViewController.h
#interface MainViewController : NSViewController <NSCollectionViewDelegateFlowLayout, NSCollectionViewDelegate, NSCollectionViewDataSource>
#end
ThoughtCollectionView.h
#interface ThoughtCollection : NSCollectionView <NSCollectionViewDataSource, NSCollectionViewDelegate, NSCollectionViewDelegateFlowLayout>
{
NSMutableArray * ar;
}
#end
ThoughtCollectionView.m
#implementation ThoughtCollection
- (NSCollectionViewItem *)collectionView:(NSCollectionView *)collectionView itemForRepresentedObjectAtIndexPath:(NSIndexPath *)indexPath{
ThoughtItems *item = [collectionView makeItemWithIdentifier:#"ThoughtItems" forIndexPath:indexPath];
NSLog(#"Reloading item");
return item;
}
- (void)collectionView:(NSCollectionView *)collectionView willDisplayItem:(nonnull NSCollectionViewItem *)item forRepresentedObjectAtIndexPath:(nonnull NSIndexPath *)indexPath{
}
- (void)collectionView:(NSCollectionView *)collectionView didEndDisplayingItem:(nonnull NSCollectionViewItem *)item forRepresentedObjectAtIndexPath:(nonnull NSIndexPath *)indexPath{
}
- (NSInteger)collectionView:(NSCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSLog(#"Collection view count : %lu", [ar count]);
return [ar count];
}
- (NSInteger)numberOfSectionsInCollectionView:(NSCollectionView *)collectionView{
return 1;
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(NSRect)newBounds
{
return YES;
}
- (void)viewDidMoveToWindow {
NSLog(#"My collection View");
self.delegate = self;
self.dataSource = self;
ar = [[NSMutableArray alloc] init];
for (int n = 0; n < 1000; n++) {
[ar addObject:#"Hello"];
}
[self reloadData];
[self setNeedsDisplay:YES];
[self layoutSubtreeIfNeeded];
}
#end
Simulator display:
enter image description here
Scroll:
enter image description here
ThoughtItem.m
#import "ThoughtItems.h"
#interface ThoughtItems ()
#end
#implementation ThoughtItems
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor orangeColor] CGColor]];
}
#end
ThoughtItem.h
#import <Cocoa/Cocoa.h>
#interface ThoughtItems : NSCollectionViewItem
#end
I found out that what's the problem with the CollectionItem.
I have to add an Object in the ThoughtItem.xib file, then change the object class name to "ThoughtItem".
And I change -(void)viewDidMoveToWindow to a method which I can call it from MainViewController.
(or create NSCollectionView in the MainViewController is a way to solve it too)
Then all the problems are solved!

how to create custom UICollectionViewCell

I have a UICollectionView and Im trying to set a label and an image in the collectionViewCell. Unfortunately I cant seem to get any labels to display or anything else for that matter.
Here is my code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)];
if(indexPath.item %2 == 0){
cell.backgroundColor=[UIColor blueColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
else {
cell.backgroundColor=[UIColor redColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
}
Unfortunately no label is being displayed and neither is the text in the label.
Updated: I've added the rest of the code from this class file.
#import "ContainerListController.h"
#import "ContainerController.h"
#import "ContainerList.h"
#implementation ContainerListController
//Deallocate temp variables
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//Initiate objects
- (id)init {
if (self = [super initWithTitle:LocStr(#"CONTAINER_LIST_TITLE") navBarHidden:NO]) {
m_paths = [ContainerList shared].paths;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(onContainerListDidChange)
name:kSDKLauncherContainerListDidChange object:nil];
}
return self;
}
//Load all the views.
- (void)loadView {
//Allocate a UI view
self.view = [[UIView alloc] init];
//Create flow layout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//Force Horizontal Scroll
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
layout.minimumInteritemSpacing =[[UIScreen mainScreen] bounds].size.width;
layout.minimumLineSpacing=0.0;
//Create Collection
UICollectionView *coll =[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
//Allocations
m_coll = coll;
coll.dataSource =self;
coll.delegate =self;
coll.pagingEnabled = YES;
coll.collectionViewLayout = layout;
//Customize Cells
[coll registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[coll setBackgroundColor:[UIColor orangeColor]];
[layout invalidateLayout];
//Create the subview
[self.view addSubview:coll];
//set minimum spacing
/*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(#"Changed to landscape Spacing");
layout.minimumLineSpacing = 100.0f;
layout.minimumInteritemSpacing = 100.0f;
}
else{
layout.minimumLineSpacing = 40.0f;
layout.minimumInteritemSpacing = 40.0f;
}*/
//Old Layout
//UITableView *table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
//m_table = table;
//table.dataSource = self;
//table.delegate = self;
//[self.view addSubview:table];
}
- (void)onContainerListDidChange {
m_paths = [ContainerList shared].paths;
[m_table reloadData];
[m_coll reloadData];
}
//Debugging components function
/*-(void)printComps:(NSArray* ) components{
for (NSInteger i =0; i<16; i++) {
NSString * item;
item=components[i];
}
}*/
//old tableview cell
- (UITableViewCell *)
tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSString *path = [m_paths objectAtIndex:indexPath.row];
NSArray *components = path.pathComponents;
cell.textLabel.text = (components == nil || components.count == 0) ?
#"" : components.lastObject;
return cell;
}
//Old tableView
- (void)
tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *path = [m_paths objectAtIndex:indexPath.row];
ContainerController *c = [[ContainerController alloc] initWithPath:path];
if (c != nil) {
[self.navigationController pushViewController:c animated:YES];
}
NSLog(#"Selected an item");
}
//old TableView count for epubs
- (NSInteger)
tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section{
return m_paths.count;
}
- (void)viewDidLayoutSubviews {
//m_table.frame = self.view.bounds;
m_coll.frame = self.view.bounds;
}
//Collection View Cell Data Allocation
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)];
//UICollectionViewCell *content = [[UICollectionViewCell alloc] init];
if(indexPath.item %2 == 0){
cell.backgroundColor=[UIColor blueColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
else {
cell.backgroundColor=[UIColor redColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
NSString *path = [m_paths objectAtIndex:indexPath.row];
NSArray *components = path.pathComponents;
NSString *Title = components.lastObject;
NSLog(#"Title: %#",Title);
NSString *Titletest = components.lastObject;
NSInteger comp1 = components.count;
NSString *comps = #"components";
NSLog(#"There are: %ld %#", (long)comp1,comps);
NSLog(#"Title: %#",Titletest);
for (NSInteger i =0; i<15; i++) {
NSString * item;
item=components[i];
NSLog(#"Component:%ld %#",(long)i,components[i]);
}
return cell;
}
//Collection View Cell Data De-Allocation
- (void)
collectionView:(UICollectionView *)collectionView
numberofItemsInSection:(NSIndexPath *)indexPath{
[collectionView deselectItemAtIndexPath:indexPath animated:YES];
NSString *path = [m_paths objectAtIndex:indexPath.row];
ContainerController *c = [[ContainerController alloc] initWithPath:path];
if(c !=nil){
[self.navigationController pushViewController:c animated:YES];
}
}
//Collection
-(NSInteger)
collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section{
return m_paths.count;
}
//Set Collection View Cell Size
-(CGSize)
collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//Set Landscape size of cells
/*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-360;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-60;
NSLog(#"Is Landscape");
return CGSizeMake(cellWidth, cellHeigt);
}
//Set Potrait size of cells
else{
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-60;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-160;
NSLog(#"Is Portrait");
return CGSizeMake(cellWidth, cellHeigt);
}*/
return CGSizeMake(collectionView.bounds.size.width, collectionView.bounds.size.height);
}
//Collection View Cell Position
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)){
return UIEdgeInsetsMake(150.0,0.0,150.0,0.0); // top, left, bottom, right
}
else{
return UIEdgeInsetsMake(20.0,0.0,0.0,0.0); // top, left, bottom, right
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
[m_coll performBatchUpdates:nil completion:nil];
}
-(void)viewWillTransitionToSize:withTransitionCoordinator{
[m_coll performBatchUpdates:nil completion:nil];
}
/*-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)
collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - ((cellCount-1) * (cellWidth + cellSpacing))) * 0.5;
inset = MAX(inset, 0.0);
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(#"Changed to landscape Spacing");
return inset;
}
else{
return inset;
}
}*/
#end
Clear example to use custom collectionViewCell.
Create a separate class subclass ofUICollectionViewCell see below code:
.h file:
#import <UIKit/UIKit.h>
#interface CollectionViewCell : UICollectionViewCell
#property (weak, nonatomic) IBOutlet UILabel *customLabel;
#end
.m file:
#import "CollectionViewCell.h"
#implementation CollectionViewCell
#end
Now drag and drop the collectionView inside viewController using storyboard then by selecting cell set custom class for it and connect its IBOutlet of label see below image.
Setting up custom class:
Connecting label's outlet: if adding label and other ui component from storyboard
Note: Drag uilabel inside cell before you connect its IBOutlet.
Now configure cell inside your viewController class. And configure collectionView correctly by connecting its delegate, dataSuorce and IBOutlet.
#import "ViewController.h"
#import "CollectionViewCell.h"
#interface ViewController (){
// instance variable deceleration part
NSMutableArray *yourArray;
}
#end
#implementation ViewController
- (void)viewDidLoad{
[super viewDidLoad];
_yourCollView.delegate = self;
_yourCollView.dataSource = self;
yourArray = [[NSMutableArray alloc] initWithObjects:#"1st cell",#"2nd cell",#"3rd cell",#"4th cell", nil];
// Do any additional setup after loading the view, typically from a nib.
}
// collection view delegate methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [yourArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"MyCustomCell" forIndexPath:indexPath];
// configuring cell
// cell.customLabel.text = [yourArray objectAtIndex:indexPath.row]; // comment this line if you do not want add label from storyboard
// if you need to add label and other ui component programmatically
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height)];
label.tag = 200;
label.text = [yourArray objectAtIndex:indexPath.row];
// this adds the label inside cell
[cell.contentView addSubview:label];
return cell;
}
//Note: Above two "numberOfItemsInSection" & "cellForItemAtIndexPath" methods are required.
// this method overrides the changes you have made to inc or dec the size of cell using storyboard.
- (CGSize)collectionView:(UICollectionView *)collectionView layout: (UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100, 100);
}
} // class ends
Setup the cell identifier (by selecting a cell) MyCustomCell you have given inside cellForItemAtIndexPath method before use see below image:
Note: Change the text color of uilabel to white before because by default collectionView appears black.
Hope here you understand.
Create subclass of UICollectionViewCell. For instance TestCollectionViewCell.
In Storyboard drag label in cell and set "Custom class" for this UICollectionViewCell with your created class. Set Reusable identifier, if your collection view in UIViewController don't forget to set DataSource and Delegate for that collectionView.
Connect IBOutlet in your Cell subclass.
Set at least 1 value inside numberOfItemsInSection method.
Then use your subclass of cell in cellForItemAt and try set text for a label.
You are missing the:
[cell.contentView addSubview:issue];

Working with collectionView and collectionViewCells

 It's the first time i'm working with UICollectionView and UICollectionViewCells. I am trying to make a simple view. The problems i' facing are: reloading collection view data, displaying text (from array) into cell labels..
code is here..
please help as much as you can.. <3 (app crashes when i don't add subview)
#import "MainCollectionViewController.h"
#import "MainCollectionViewCell.h"
#interface MainCollectionViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
{
UICollectionView *colView;
}
#end
#implementation MainCollectionViewController
static NSString * const reuseIdentifier = #"Cell";
- (void)viewDidLoad {
[super viewDidLoad];
// [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
self.actressArray = [NSMutableArray arrayWithObjects:#"John", #"Patrick", #"Jack", #"Clara", #"Nicol", #"Amanda", #"Nick", #"Bob", #"Jeff", #"Jerremy", #"Gloria", #"Bred", #"Seth", #"Peter", #"Lous", nil];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
colView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[colView setDataSource:self]; //დელეგატების კოდით ჩართვა
[colView setDelegate:self];
[colView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
[colView setBackgroundColor:[UIColor grayColor]]; //ვიუს ბექგრაუნდის ფერი
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView setCollectionViewLayout:flowLayout];
[self.view addSubview:colView]; //ვიუზე ჩვენ მიერ გამზადებული ვიუს დაგდება
[self.collectionView registerClass:[MainCollectionViewCell class] forCellWithReuseIdentifier: reuseIdentifier];
////[self.collectionView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//// In a storyboard-based application, you will often want to do a little preparation before navigation
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender //{
//}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return _actressArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MainCollectionViewCell *cell = (MainCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
NSString *actressStr = [_actressArray objectAtIndex:indexPath.row];
cell.actressLabel.text = actressStr;
//[self.collectionView reloadData];
//[cell.contentView addSubview: ];
return cell;
}
1 Please Check You Outlets Connection Once again :-
2 And What's Error ???
here is updated one. reload data doesn't works
#import "MainCollectionViewController.h"
#import "MainCollectionViewCell.h"
#interface MainCollectionViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
{
UICollectionView *colView;
}
#end
#implementation MainCollectionViewController
static NSString * const reuseIdentifier = #"Cell";
- (void)viewDidLoad {
[super viewDidLoad];
// [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
self.actressArray = [NSMutableArray arrayWithObjects:#"John", #"Patrick", #"Jack", #"Clara", #"Nicol", #"Amanda", #"Nick", #"Bob", #"Jeff", #"Jerremy", #"Gloria", #"Bred", #"Seth", #"Peter", #"Lous", nil];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
colView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[colView setDataSource:self]; //დელეგატების კოდით ჩართვა
[colView setDelegate:self];
[colView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
[colView setBackgroundColor:[UIColor grayColor]]; //ვიუს ბექგრაუნდის ფერი
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView setCollectionViewLayout:flowLayout];
[self.view addSubview:colView]; //ვიუზე ჩვენ მიერ გამზადებული ვიუს დაგდება
[self.collectionView registerClass:[MainCollectionViewCell class] forCellWithReuseIdentifier: reuseIdentifier];
[colView reloadData];
}
//// In a storyboard-based application, you will often want to do a little preparation before navigation
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _actressArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MainCollectionViewCell *cell = (MainCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
cell.layer.cornerRadius = 10;
cell.layer.borderWidth = 2.0;
cell.layer.borderColor = [[UIColor lightGrayColor] CGColor];
UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, cell.bounds.size.width -20 , cell.bounds.size.height)];
testLabel.text = _actressArray[indexPath.row];
testLabel.font = [UIFont fontWithName:#"Helvetica" size:12];
testLabel.textAlignment = NSTextAlignmentCenter;
testLabel.lineBreakMode = NSLineBreakByWordWrapping;
testLabel.numberOfLines = 0;
[cell.contentView addSubview:testLabel];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(collectionView.frame.size.width/3.2 , 100);
} //ხაზზე სამისთვის

multiple selection in uicollectionview not working in ios

i have multiple image in uicollectionview like grid view. i want select multiple image at a time but not working this code.please any one give idea about this code.
i have already tried this code but not working.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath: (NSIndexPath *)indexPath
{
NSMutableArray *indexPaths = [NSMutableArray arrayWithObject:indexPath];
if (self.selectedItemIndexPath)
{
// if we had a previously selected cell
if ([indexPath compare:self.selectedItemIndexPath] == NSOrderedSame)
{
// if it's the same as the one we just tapped on, then we're unselecting it
self.selectedItemIndexPath = nil;
}
else
{
// if it's different, then add that old one to our list of cells to reload, and
// save the currently selected indexPath
[indexPaths addObject:self.selectedItemIndexPath];
self.selectedItemIndexPath = indexPath;
}
}
else
{
// else, we didn't have previously selected cell, so we only need to save this indexPath for future reference
self.selectedItemIndexPath = indexPath;
}
// and now only reload only the cells that need updating
[self.collectionView reloadItemsAtIndexPaths:indexPaths];
}
// I Have Drag the UICollectionView Controller in storyboard
static NSString * const reuseIdentifier = #"Cell";
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
arrImage = [[NSMutableArray alloc]initWithObjects:#"1.jpeg",#"2.jpeg",#"3.jpeg",#"4.jpeg",#"5.jpeg",#"6.jpeg",#"7.jpeg",#"8.jpeg",#"9.jpeg",#"10.jpeg",#"flower.jpeg",#"flower1.jpeg", nil];
[self.collectionView setAllowsMultipleSelection:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [arrImage count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[arrImage objectAtIndex:indexPath.row]];
[self.view addSubview:recipeImageView];
cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:[arrImage objectAtIndex:indexPath.row]]];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell* cell=[self.collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [[UIColor yellowColor] colorWithAlphaComponent:0.15];
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell* cell=[self.collectionView cellForItemAtIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[arrImage objectAtIndex:indexPath.row]];
}