Add images from UIImagePickerViewController to UICollectionView inside UITableViewCell - ios

At first, sorry for my long question.
I'm creating an custom UITableViewCell with UICollectionView inside it. Whenever users select this cell, UIImagePickerController will appear, and now I wanna pass all selected images from UIImagePickerController into UICollectionView inside my custom cell. I was completed to show image picker and now my problem is display selected images in collection view.
How can I make it?
My code:
SHImageUploadCell.h
#import <UIKit/UIKit.h>
#class SHImageUploadCell;
#protocol SHImagUploadDelegate<NSObject>
#optional
- (void)closeImage:(SHImageUploadCell*)cell;
#end
#interface SHImageUploadCell : UICollectionViewCell
#property (weak, nonatomic) IBOutlet UIImageView *imgUpload;
#property (strong,nonatomic) id<SHImagUploadDelegate> delegate;
#property(nonatomic) int imageIndex;
#property (weak, nonatomic) IBOutlet UIImageView *bugImage;
#end
SHImageUploadCell.m
#import "SHImageUploadCell.h"
#implementation SHImageUploadCell
- (IBAction)bntDeleteImageClick:(id)sender {
NSDictionary* userInfo = #{#"index": #(self.imageIndex)};
NSLog(#"%d", self.imageIndex);
if (_delegate) {
[_delegate closeImage:self];
}
}
#end
MyCustomCell.h
#import <UIKit/UIKit.h>
#interface SHPhotoPickerViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UICollectionView *photoCollection;
#property (strong, nonatomic) NSMutableArray *listImage;
#end
MyCustomCell.m
#import "SHPhotoPickerViewCell.h"
#import "SHImageUploadCell.h"
#interface SHPhotoPickerViewCell ()<UICollectionViewDataSource, UICollectionViewDelegate, SHImagUploadDelegate>
#end
#implementation SHPhotoPickerViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
[self.photoCollection registerClass:[SHImageUploadCell class] forCellWithReuseIdentifier:#"selectedCell"];
[self.photoCollection registerNib:[UINib nibWithNibName:#"SHImageUploadCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:#"selectedCell"];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.listImage.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
SHImageUploadCell *uploadCell = [collectionView dequeueReusableCellWithReuseIdentifier:#"uploadCell" forIndexPath:indexPath];
uploadCell.imgUpload.image = [UIImage imageWithData: self.listImage[indexPath.row]];
uploadCell.imageIndex = (int)indexPath.row;
uploadCell.delegate=self;
return uploadCell;
}
#end
Handle cell select:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 4){
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];
}
}
}
UIImagePickerController delegate:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
SHPhotoPickerViewCell *photoPickerCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.pickerCellIndexPath.row inSection:1]];
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
image = [SHHelper resizeImageWithImage:image toSize:CGSizeMake(480, 320)];
NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
photoPickerCell.listImage = [NSMutableArray new];
[photoPickerCell.listImage addObject:imageData];
[photoPickerCell.photoCollection reloadData];
[picker dismissViewControllerAnimated:YES completion:^{
}];
}

Try this :
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
id object = [listImage objectAtIndex:indexPath.row];
if ([object isKindOfClass:[UIImage class]]) {
uploadCell.imgUpload.image = (UIImage *)object;
}
else{
uploadCell.imgUpload.image = [UIImage imageWithData: object];
}
return uploadCell;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[listImage addObject:image]; // here add image which you selected
// reload tableview
// reload collection view
[picker dismissViewControllerAnimated:YES completion:^{
}];
}

Related

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

Objective C - Passing/retrieving selected image from UIImageView to second VC with tableview so cell can display that image

i already passed input text with prepareForSegue, text into mutablearray, then passing that array with prepareforeSegue to second VC with tableview so table cell now displays name. But what with selected/picked image in uIImageView in first vc so table cell in second VC can display image in a row next to name? i manage to do it with image from imagexxassets i followed the same logic like passing text but keep failing.
VIewController.h
#import <UIKit/UIKit.h>
#import "TableViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#interface ViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
#property (strong, nonatomic) IBOutlet UITextField *inputName;
#property (nonatomic) NSMutableArray *items;
//#property (nonatomic) NSMutableArray *images;
- (IBAction)AddData:(id)sender;
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UIButton *selectPhoto;
#property (strong, nonatomic) IBOutlet UIButton *takePhotoFromCamera;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_items = [[NSMutableArray alloc]init];
//_images = [[NSMutableArray alloc]init];
[self.takePhotoFromCamera addTarget:self action:#selector(_takePhoto) forControlEvents:UIControlEventTouchUpInside];
[self.selectPhoto addTarget:self action:#selector(_selectPhoto) forControlEvents:UIControlEventTouchUpInside];}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)AddData:(id)sender
{
//[_images addObject:self.imageView.image];
//[_images insertObject:self.imageView.image atIndex:0];
if ([self.inputName.text length]> 0)
{
[_items addObject:self.inputName.text];
//[_images addObject:self.imageView.image];
[self performSegueWithIdentifier:#"tableSegue" sender:self];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Error"
message:#"You must enter some data"
delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
}
- (void)addItemViewController:(TableViewController *)controller didFinishSelectingItem:(NSMutableArray *)item selectedTag:(int)tag{
NSLog(#"DATA=%#", item);
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"tableSegue"])
{
TableViewController *controller = (TableViewController *)segue.destinationViewController;
controller.items = _items;
//TableViewController *controller1 = (TableViewController *)segue.destinationViewController;
//controller1.images = _images;
NSLog(#"%#",self.inputName.text);
self.inputName.text = NULL;
}
}
#pragma mark code for images
-(void)_takePhoto
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)_selectPhoto
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:NO completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
}
}
-(void)imagePickerControllerDidCancel:
(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
TableViewController.h
#import <UIKit/UIKit.h>
//using delegate
#protocol TableViewControllerDelegate <NSObject>
- (void)addItemViewController:(id)controller didFinishSelectingItem:(NSMutableArray *)item selectedTag:(int)tag;
#end
//extra attention here
#interface TableViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
// id of delegate
#property (nonatomic, weak) id <TableViewControllerDelegate> delegate;
#property (nonatomic) NSMutableArray *items;
//#property (nonatomic) NSMutableArray *images;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
TableViewController.m
#import "TableViewController.h"
#interface TableViewController ()
#end
#implementation TableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// code for reversing objects in array so tableview can put new rows on top
//_items = [[[_items reverseObjectEnumerator] allObjects] mutableCopy];
self.tableView.delegate = self;
self.tableView.dataSource = self;
// setting invisible footer to display only rows which contains data and to remove border lines in tableview
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 10.0f)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:#"BasicCell" forIndexPath:indexPath];
//NSString *lijevaSlika = [NSString stringWithFormat:#"dice%i", sum];
//[questionTexts objectAtIndex:0]
//NSString *selectedImage = [NSString stringWithFormat:_images];
myCell.imageView.image = [UIImage imageNamed:#"2.png"];
myCell.textLabel.text = _items[indexPath.row]; //name of objects in array are displayed in cells
myCell.textLabel.textColor = [UIColor blueColor]; //changing color of text in cell
//changing background of cell
/*myCell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"back.png"]];
myCell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"front.png"]];
*/
return myCell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.items count]; //objects in arrays - rows in table
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[_items removeObjectAtIndex:indexPath.row]; //swipe to left do delete row
[self.tableView reloadData];
}
/*- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//selected row returns to previous viewcontroller
[self.navigationController popViewControllerAnimated:YES];
}
*/
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
First you have to store selected images in array then you have to pass that array in same way you are passing _items array.Then In cellForRowAtIndexPath of TableViewController add this line and check you are getting anything in _images array
myCell.imageView.image = [_images objectAtIndex:indexPath.row];

UICollectionView PrepareForSegue Image not Transferring

I have a UICollectionView that I cannot get to transfer the image to the detailview. The detailview transfer would work when I used local images and the pictures array with the [pictures[row]] method, but since using the SDWebImage framework, I cannot do that. I cannot figure out to properly transfer the image to the detail view once the cell is selected. The logic is explained in the first method CellForItemAtIndexPath. The selected cell and prepare for segue methods are causing the issue. Let me know if you need more information.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
pictureViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"MyCell" forIndexPath:indexPath];
NSString *pictures1 = [[pictures objectAtIndex:indexPath.row]objectForKey:#"filename"];
comment = [[pictures objectAtIndex:indexPath.row] objectForKey:#"comment"];
[cell.imageView setImageWithURL:[NSURL URLWithString:pictures1]
placeholderImage:[UIImage imageNamed:#"Earth.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
NSLog(#"Error downloaidng images");
}];
// UIImage *image;
// int row = [indexPath row];
//image = [UIImage imageNamed:pictures[row]];
//image = [UIImage imageWithData:imageUrl];
// cell.imageView.image = image;
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UIImage *image;
//int row = [indexPath row];
NSString *pictures1 = [[pictures objectAtIndex:indexPath.row]objectForKey:#"filename"];
// image = [UIImage imageNamed:pictures[row]];
image = [UIImage imageNamed:pictures1];
pictureDetailView *pictureDetail = [[pictureDetailView alloc]init];
pictureDetail.image = image;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UICollectionViewCell *)sender
{
pictureDetailView *targetVC = (pictureDetailView *) [segue destinationViewController];
NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
UIImage *image;
//int row = [indexPath row];
NSString *pictures1 = [[pictures objectAtIndex:indexPath.row]objectForKey:#"filename"];
// image = [UIImage imageNamed:pictures[row]];
image = [UIImage imageNamed:pictures1];
//image = [UIImage imageWithData:imageUrl];
targetVC.image=image;
}
#end
I had a similar issue in an app I'm working on, and could not find any help for Collection Views. The code I used is below (updated to match your methods). I hope this helps get you on the right track. You can also check the demo project posted on the SDWebImage GitHub page. That helped me figure some of these issues out.
In Your CollectionViewController.h:
#import <UIKit/UIKit.h>
#import "PictureDetailView.h"
#class PictureDetailView;
#interface CollectionViewController : UICollectionViewController <UICollectionViewDataSource, UICollectionViewDelegate>
#property (nonatomic, strong) PictureDetailView *detailViewController;
#end
In Your CollectionViewController.m:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"yourSegueNameHere"]) {
PictureDetailView *pictureDetail = segue.destinationViewController;
NSIndexPath *indexPath = [[self.collectionView indexPathsForSelectedItems] lastObject];
NSString *largeImageURL = [pictures1 objectAtIndex:indexPath.row];
pictureDetail.imageURL = [NSURL URLWithString:largeImageURL];
}
}
In Your DetailViewController.h
#import <UIKit/UIKit.h>
#import "CollectionViewController.h"
#interface DetailViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) NSURL *imageURL;
#end
In Your DetailViewController.m
#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImageView+WebCache.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
#synthesize imageURL = _imageURL;
#synthesize imageView = _imageView;
- (void)setImageURL:(NSURL *)imageURL
{
if (_imageURL != imageURL)
{
_imageURL = imageURL;
[self configureView];
}
}
- (void)configureView
{
if (self.imageURL)
{
[self.imageView setImageWithURL:self.imageURL
placeholderImage:nil
options:SDWebImageProgressiveDownload
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
}];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureView];
}
Just access the imageView of the selected cell and extract its image. Here is how to do it:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [self collectionView:collectionView cellForItemAtIndexPath:indexPath];
UIImage *image = cell.imageView.image;
// Pass the image to the next VC.
}
Let me know if you need more help.

UICollectionView and push to detailViewController using Parse

I use the tapGesture method to pouch the image from UICollectionView to detailViewController
viewController.h as follows:
#import <Parse/Parse.h>
#interface CardsViewController : UIViewController <UICollectionViewDelegateFlowLayout> {
NSMutableArray *allImages;
NSArray *cardFileArray;
}
#property (weak, nonatomic) IBOutlet UICollectionView *imageCollection
and viewController.m as the follow
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [cardFileArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"MyCell";
Cards *cell = (Cards *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
PFObject *imageObject = [cardFileArray objectAtIndex:indexPath.row];
PFFile *imageFile = [imageObject objectForKey:KEY_IMAGE4];
cell.spinController.hidden = NO;
[cell.spinController startAnimating];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
cell.imageView.image = [UIImage imageWithData:data];
[cell.spinController stopAnimating];
cell.spinController.hidden = YES;
}
}];
return cell;
}
- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture{
CGPoint touchPoint = [gesture locationInView:imageCollection];
NSUInteger touchPage = floorf(touchPoint.x / imageCollection.frame.size.width);
NSIndexPath *indexPath = [imageCollection indexPathForItemAtPoint:touchPoint];
if (indexPath == nil) {
touchPage = touchPage % ([allImages count]);
}
//Push the image to another view
detailViewController*ptvc = [self.storyboard instantiateViewControllerWithIdentifier:#"imageDetail"];
[self.navigationController pushViewController:ptvc animated:YES];
ptvc.imageString = [cardFileArray objectAtIndex:touchedPage];
}
the detailViewController.h as follow
#property (strong, nonatomic) IBOutlet UIImageView *Preview;
#property (strong, nonatomic) UIImage *imagePreview;
so for the DetailViewController i put in viewDidload this line
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//self.imageView.image = [UIImage imageNamed:self.imageViewDetail];
self.Preview.image = self.imagePreview;
}
but the app make crash and mark the line on the viewDidload
; so any advice i need to puch the image on uicollectionView to detailView
to solve this first you need to identify the image in didselect from parse and declare the segue as well as following
[self performSegueWithIdentifier:#"showDetails" sender:imageCollection];
PFObject *object = [cardFileArray objectAtIndex:indexPath.row];
PFFile *file = [object objectForKey:KEY_IMAGE4];
[file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
Cards *recipe = [[Cards alloc] init];
recipe.imageView.image = [UIImage imageWithData:data];
}
}];
then you perform the Segue method and link to the detail view as normal and not the following
link you segue to the "you cell" and the imageview in the cell
Finally, import your cell to the detail view and declare it in your header file (this will be linked to your segue)
i hope this will help you
Two things
Remove the tap gesture recognizer and use
-(void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
I see you are using storyboards.. just connect the two view controllers by a push segue. Set an UIImage as property of the detailViewController
-(void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//store indexPath.row to a variable accessible outside this function
selectedRow = indexPath.row;
[self performSegueWithIdentifier:#"detail" sender:nil];
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
DetailViewController *detail = [segue destinationViewController];
[detail setImageForDetail:[UIImage imageWithData:[allImages objectAtIndex:selectedRow]]];
//imageArray is the array used to populate the imageCollectionView and i assume they are stored as NSDATA
}
in DetailViewController.h, add
#property (strong,nonatomic) UIImage *imageForDetail;
in DetailViewController.m viewDidLoad add,
self.Preview.image = self.imageForDetail;

Placing UIImage at tapped image in UITableViewCell

Currently I have custom UITablViewCell's (BIDSelectBusinessCustomCell) that are displayed in a tableView (myTableView). The custom cell is made up of a UIImageView and a label. When the view loads the labels are populated with the strings from my model. UIImageViews are blank. I want to be able for a user to 'tap' the UIImageView, select a picture from what is stored on their phone and for that image to be saved to the UIImageView.
From the below code I can get the 'tap' gesture, then the pickercontroller pops up and a user selects an image. The way the code is now one image that is selected is set for all of the UIImageViews. Which is understandable. But I want it to be set to that particular UIImageView and don't know how to.
Code:
#import <UIKit/UIKit.h>
#interface BIDBusinessSelectViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
#property (strong, nonatomic) NSArray *linkedBusinessParseArray;
//Stores the array of models
#property (strong, nonatomic) NSMutableArray *linkedBusinessParseModelArray;
#property NSUInteger relevantIndex;
#property (strong, nonatomic) UIImage *tempImageHolder;
#end
#import "BIDBusinessSelectViewController.h"
#import <Parse/Parse.h>
#import "BIDBusinessModel.h"
#import "BIDSelectBusinessCustomCell.h"
#interface BIDBusinessSelectViewController () <ImageSelect>
{
BIDSelectBusinessCustomCell *aCell;//define a cell of ur custom cell to hold selected cell
UIImage *choosenImage; //image to set the selected image
}
#end
#implementation BIDBusinessSelectViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
self.linkedBusinessParseModelArray = [[NSMutableArray alloc]init];
//create query
PFQuery *linkedBusinessParseQuery = [PFQuery queryWithClassName:#"linkedBusinessParseClass"];
//follow relationship
[linkedBusinessParseQuery whereKey:#"currentBusinessUserParse" equalTo:[PFUser currentUser]];
[linkedBusinessParseQuery whereKey:#"linkRequestSentParse" equalTo:#"Approved"];
[linkedBusinessParseQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.linkedBusinessParseArray = objects; //store them in my model array
//loop through model array from Parse
for (NSDictionary *dict in self.linkedBusinessParseArray) {
NSString *descPlaceNameParse = [dict objectForKey:#"placeDescriptionParse"];
NSLog(#"descPlacesNameParse: %#",descPlaceNameParse);
PFObject *tempObj = (PFObject *) dict;
NSString *tempObjString = tempObj.objectId;
NSLog(#"tempObjString (inside dict): %#", tempObjString);
//storing values from Parse into my model
BIDBusinessModel *userModel = [[BIDBusinessModel alloc]init];
userModel.descriptionModelParse = descPlaceNameParse;
userModel.objectIdModelParse = tempObjString;
[self.linkedBusinessParseModelArray addObject:userModel];
NSLog(#"self.linkedBusinessParseModelArray: %lu", (unsigned long)[self.linkedBusinessParseModelArray count]);
//Reload tableview. Has to go here in block otherwise it does not occur
[self.myTableView reloadData];
}
}];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Device has no camera"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[myAlertView show];
}
choosenImage = [UIImage imageNamed:#"pin.png"]; //hear u need to set the image for cell assuming that u are setting initially same image for all the cell
}
#pragma mark -
#pragma mark Table Delegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.linkedBusinessParseModelArray.count; //returns count of model NSMutableArray
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Start cellforRowStIndex");
static NSString *CellIdentifier = #"Cell";
BIDSelectBusinessCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[BIDSelectBusinessCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = choosenImage;
//cell.descLabel.text = [NSString stringWithFormat:#"bid= %d",indexPath.row];//set text from the model//Omitted for my desc
cell.descLabel.text = bizModel.descriptionModelParse;
cell.logoImage.image =bizModel.image; //setting the image initially the image when u set in "viewDidLoad" method from second time onwords it will set from the picker delegate method
//insted of settig the gesture hear set it on the custom cell
cell.ImageSelectDelegate = self; //setting the delegate
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
// hear implementation of delegate method
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
{
//open up the image picker
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
aCell = (BIDSelectBusinessCustomCell *)logoImgView.superview; //her getting the cell
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *aChosenImage = info[UIImagePickerControllerEditedImage];
//UIImage holder to transfer to cellForRowAtIndexPath
choosenImage = aChosenImage;
NSIndexPath *indexPath = [self.myTableView indexPathForCell:aCell];
[self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //hear reloading the selected cell only not entire tableview
//get the model and set the choosen image
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = aChosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#protocol ImageSelect<NSObject> //for this u need use custom delegate so i did like this
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
#end
#interface BIDSelectBusinessCustomCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *descLabel;
#property (strong, nonatomic) IBOutlet UIImageView *logoImage;
#property (nonatomic, assign) id<ImageSelect>ImageSelectDelegate; // deleagte
#end
#import "BIDSelectBusinessCustomCell.h"
#implementation BIDSelectBusinessCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.logoImage = [[UIImageView alloc]init];
self.descLabel = [[UILabel alloc]init];
//set up gesture hear in the custom cell insted in the controller class
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapLogoImage:)];
[tap setNumberOfTouchesRequired:1];
[tap setNumberOfTapsRequired:1];
[tap setDelegate:self];
self.logoImage.userInteractionEnabled = YES;
[self.logoImage addGestureRecognizer:tap];
//[self addSubview:logoImage];
//[self addSubview:descLabel];
}
return self;}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)tapLogoImage:(UITapGestureRecognizer *)guesture
{
if([self.ImageSelectDelegate respondsToSelector:#selector(selectSetImageForSelectedLogImage:)])
{
[self.ImageSelectDelegate selectSetImageForSelectedLogImage:self.logoImage];//call the delegate method from the selected cell
}
}
#end
Yup for this, i tried but finally i did something like this, go through this u may find some solution. and hope this helps u :)
//in custom cell "BIDSelectBusinessCustomCell.h"
#import <UIKit/UIKit.h>
//define a delegate method that is called each time when u tapped on cell
#protocol ImageSelect<NSObject> //for this u need use custom delegate so i did like this
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
#end
#interface BIDSelectBusinessCustomCell : UITableViewCell <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
UIImageView *logoImage; //your image holder
UILabel *descLabel; //label
}
#property (nonatomic, retain) UIImageView *logoImage;
#property (nonatomic, retain) UILabel *descLabel;
#property (nonatomic, assign) id<ImageSelect>ImageSelectDelegate; // deleagte
#end
//in custom cell "BIDSelectBusinessCustomCell.m"
#import "BIDSelectBusinessCustomCell.h"
#implementation BIDSelectBusinessCustomCell
#synthesize logoImage;
#synthesize descLabel;
#synthesize ImageSelectDelegate;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
logoImage = [[UIImageView alloc]init];
descLabel = [[UILabel alloc]init];
//set up gesture hear in the custom cell insted in the controller class
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapLogoImage:)];
[tap setNumberOfTouchesRequired:1];
[tap setNumberOfTapsRequired:1];
[tap setDelegate:self];
logoImage.userInteractionEnabled = YES;
[logoImage addGestureRecognizer:tap];
[self addSubview:logoImage];
[self addSubview:descLabel];
}
return self;
}
- (void)dealloc
{
[logoImage release];
[descLabel release];
[super dealloc];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)layoutSubviews
{
//in this method simply i am setting the frames of subviews
[super layoutSubviews];
self.logoImage.frame = CGRectMake(130, 2, 44,44 );
self.descLabel.frame = CGRectMake(20, 2, 60, 44);
}
- (void)tapLogoImage:(UITapGestureRecognizer *)guesture
{
if([self.ImageSelectDelegate respondsToSelector:#selector(selectSetImageForSelectedLogImage:)])
{
[self.ImageSelectDelegate selectSetImageForSelectedLogImage:self.logoImage];//call the delegate method from the selected cell
}
}
#end
//in your view controller class u need to do something like this ;)
//ViewController.h file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (retain, nonatomic) IBOutlet UITableView *aTableView;
#property (nonatomic, retain) NSIndexPath *selectedIndexPath; //no need just try
#end
//in your "ViewController.m" file
#interface ViewController ()<UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControll erDelegate,ImageSelect>//delegate
{
BIDSelectBusinessCustomCell *aCell;//define a cell of ur custom cell to hold selected cell
UIImage *choosenImage; //image to set the selected image
}
- (void)viewDidLoad
{
[super viewDidLoad];
choosenImage = [UIImage imageNamed:#"Star.png"]; //hear u need to set the image for cell assuming that u are setting initially same image for all the cell
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[aTableView release];
[super dealloc];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 4; //pass array check array contains valid objects
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BIDSelectBusinessCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell == nil)
{
cell = [[BIDSelectBusinessCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = aChosenImage;
cell.descLabel.text = [NSString stringWithFormat:#"bid= %d",indexPath.row];//set text from the model
cell.logoImage.image =bizModel.image; //setting the image initially the image when u set in "viewDidLoad" method from second time onwords it will set from the picker delegate method
//insted of settig the gesture hear set it on the custom cell
cell.ImageSelectDelegate = self; //setting the delegate
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
// hear implementation of delegate method
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
{
//open up the image picker
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
aCell = (BIDSelectBusinessCustomCell *)logoImgView.superview; //her getting the cell
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *aChosenImage = info[UIImagePickerControllerEditedImage];
//UIImage holder to transfer to cellForRowAtIndexPath
choosenImage = aChosenImage;
NSIndexPath *indexPath = [aTableView indexPathForCell:aCell];
[self.aTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //hear reloading the selected cell only not entire tableview
//get the model and set the choosen image
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = aChosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
Yes it is true this would set the image to every row..
Now what you can do is : -
While loading of tableViewCells just assign the tag of UIImageView as the (indexPath.Row).
This would assign unique tags to the ImageView.
You can easily get the tag of that imageView while tapping and now you can assign the image to particular imageView through tagValue of that imageView.
This would assign image to a particular imageView as all have unique tags.
Hope you got the answer of your problem.

Resources