Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
How to select the Collection View cell images using allows multiple selection is not working. Please suggest me idea or links
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"photo viewer");
[self.collectionView setPagingEnabled:NO];
self.collectionView.allowsSelection=YES;
[self.collectionView registerClass:[CWPhotoGalleryCell class]
forCellWithReuseIdentifier:CWPhotoGalleryCellIdentifier];
[self.collectionView scrollToItemAtIndexPath:self.selectedIndexPath atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:
(NSInteger)section
{
return [self.imageArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CWPhotoGalleryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CWPhotoGalleryCellIdentifier
forIndexPath:indexPath];
cell.navigationControllerContainer = self.navigationController;
ALAsset *photo = [self.imageArray objectAtIndex:indexPath.row];
ALAssetRepresentation *rep = [photo defaultRepresentation];
CGImageRef ref = [rep fullScreenImage];
UIImage *img = [[UIImage alloc] initWithCGImage:ref];
cell.image = img;
NSLog(#"clicked");
return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return self.view.bounds.size;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
To select single or multiple items in collection view you need to implement UIColectionViewDelegate. You also need to add NSMutableArray where you will keep selected items (selectedItems).
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
Item *item = self.yourArray[indexPath.row];
[selectedItems addObject: item];
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
Item *item = self.yourArray[indexPath.row];
[selectedItems removeObject:item];
}
The last thing left to do is add button to toogle between selected and non-selected state:
-(IBAction)toogleButtonPressed:(id)sender
{
UIBarButtonItem *toogleButton = (UIBarButtonItem *)sender;
if (!self.selected)
{
self.selected = YES;
[toogleButton setTitle:#"Done"];
[self.collectionView setAllowsMultipleSelection:YES];
}
else
{
self.selected = NO;
[toogleButton setTitle:#"Select"];
[self.collectionView setAllowsMultipleSelection:NO];
for(NSIndexPath *iP in self.collectionView.indexPathsForSelectedItems)
{
[self.collectionView deselectItemAtIndexPath:iP animated:NO];
}
[selectedItems removeAllObjects];
}
}
Hope this help.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is the way i am working on header.
// viewDidLoad
[self.collectionView registerClass:[UICollectionViewCell class]forCellWithReuseIdentifier:#"Cell"];
[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"header"];
UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 390, 300) collectionViewLayout:layout];
layout.collectionView.backgroundColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0];
[self.collectionView registerClass:[UICollectionViewCell class]
forCellWithReuseIdentifier:#"Cell"];
self.collectionView.delegate=self;
self.collectionView.dataSource=self;
layout.minimumInteritemSpacing = 15;
[layout setScrollDirection:UICollectionViewScrollDirectionVertical];
self.collectionView.collectionViewLayout = layout;
self.collectionView.showsHorizontalScrollIndicator = NO;
self.collectionView.showsVerticalScrollIndicator = NO;
[self.collectionView setBounces:YES];
self.collectionView.allowsMultipleSelection = YES;
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"HorizontalPickerCell"];
[self.view addSubview:self.collectionView];
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
if (section == 0) {
return CGSizeMake(0, kHeaderHeight);
}
return CGSizeMake(0, kHeaderHeight + kInterSectionMargin);
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
NSLog(#"levels count:%d", [arrLevels count]);
return [arrLevels count];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
NSLog(#"vals count:%d", [arrSeats count]);
for(int i=0; i<[arrLevels count]; i++)
{
if(section == i)
{
int c;
NSString *cnt = [NSString stringWithFormat:#"%#",[arrTot objectAtIndex:i]];
c = [cnt intValue];
return c;
}
}
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
//cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"blue_s.png"]];
if (cell.selected) {
[UIColor colorWithPatternImage:[UIImage imageNamed:#"blue_s.png"]]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"yellow_seat.png"]]; // Default color
}
return cell;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(10, 12, 10, 10);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout: (UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize retval = CGSizeMake(22, 20);
return retval;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableview = nil;
if (kind == UICollectionElementKindSectionHeader) {
UICollectionReusableView *headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:nil forIndexPath:indexPath];
self.lblHeader = [[UILabel alloc]initWithFrame:CGRectMake(120, 10, 100, 30)];
self.lblHeader.backgroundColor = [UIColor whiteColor];
self.lblHeader.textColor = [UIColor redColor];
self.lblHeader.text = #"Level 1";
[self.collectionView addSubview:self.lblHeader];
}
return reusableview;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
printf("Selected View index=%d",indexPath.row);
itemPaths = [self.collectionView indexPathsForSelectedItems];
UICollectionViewCell* cell=[self.collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"blue_s.png"]];
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell* cell=[self.collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"yellow_seat.png"]];
}
The error you're seeing is pretty clear. You're trying to dequeue a reusable view but the collection view doesn't know anything about the reuse identifier you're passing.
You need to call registerClass:forSupplementaryViewOfKind:withReuseIdentifier: before dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: is called. I typically call one of the register methods in viewDidLoad so all the setup is done and I can just call the dequeue method. If you're loading your custom header and footer views from nib you can use the registerNib:forSupplementaryViewOfKind:withReuseIdentifier: method.
Edit
I see you updated the code. You need to move these lines
UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 390, 300) collectionViewLayout:layout];
above the lines where you're calling the register class methods. You cannot send messages to an object before you allocate and initialize it.
If you are not displaying anything on the header then how could you expect header view to show you something on header part of UICollectionView.Try following code.This is working code
- (void)viewDidLoad
{
arry=[[NSArray alloc] initWithObjects:#"One",#"Two",#"Three",#"Four", nil];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"HeaderView"];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [arry count];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 20;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
if (cell==nil) {
cell=[[UICollectionViewCell alloc] init];
}
UILabel *label = (UILabel*)[cell.contentView viewWithTag:21];
if (label==nil) {
label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
label.tag = 21;
[cell.contentView addSubview:label];
}
label.text = [arry objectAtIndex:indexPath.row];
NSLog(#"cell is %#",NSStringFromCGRect(cell.frame));
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(60, 60);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
UIEdgeInsets insets=UIEdgeInsetsMake(10, 10, 10, 10);
return insets;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
UICollectionReusableView *reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"HeaderView" forIndexPath:indexPath];
if (reusableview==nil) {
reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
}
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
label.text=[NSString stringWithFormat:#"Recipe Group #%i", indexPath.section + 1];
[reusableview addSubview:label];
return reusableview;
}
return nil;
}
why are you adding lblHeader to self.collectionView add to headerView.And return headerView.Replace your code with it
if (kind == UICollectionElementKindSectionHeader) {
UICollectionReusableView *headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:nil forIndexPath:indexPath];
self.lblHeader = [[UILabel alloc]initWithFrame:CGRectMake(120, 10, 100, 30)];
self.lblHeader.backgroundColor = [UIColor whiteColor];
self.lblHeader.textColor = [UIColor redColor];
self.lblHeader.text = #"Level 1";
// [self.collectionView addSubview:self.lblHeader];
[headerView addSubview:self.lblHeader];
return headerView;
}
Typically you put this register line in the viewDidLoad or some sort of initialize so that it is not called over and over again. But mainly you have some confusion. You register a class for the header but you dequeue a class on the footer. You should register a class for both and dequeue the right one for each.
Notice your register uses UICollectionElementKindSectionHeader:
[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"header"];
Notice your dequeue uses UICollectionElementKindSectionFooter :
UICollectionReusableView *supplementaryView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:#"header" forIndexPath:indexPath];
hope that helps.
try this :
//ON top
static NSString *headerViewIdentifier = #"Test Header View";
static NSString *footerViewIdentifier = #"Test Footer View";
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = nil;
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
identifier = headerViewIdentifier;
}
else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
identifier = footerViewIdentifier;
}
// TODO Setup view
UICollectionReusableView *supplementaryView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:identifier forIndexPath:indexPath];
return supplementaryView;
}
i want to attech UIActivityIndicator with UITableView when then first time table load on iphone activity must start blinking and when the table compleletely load in iphone when i click on load more cell then also i want to show activity blink for that moment when more rows loading kindly tell me how can i do that this is the code if you complete this code by your self then thanks in advance
#import "RootViewController.h"
#import "Tweet.h"
#implementation RootViewController
#synthesize customImage,pagecontrol,cell;//indexPath;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad
{
pageSize = 2;
// totalpages =(NSInteger) (xmlParser.tweets)/5 ;
xmlParser = [[XMLParser alloc] loadXMLByURL:#"http://api.twitter.com/1/statuses/user_timeline/KentFranks.xml"];
[super viewDidLoad];
self.title = #"Tweets";
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if([xmlParser.tweets count]>pageSize)
{
return pageSize+1;
}
return xmlParser.tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
//UIImage *twitterLogo = [[UIImage imageNamed:#"twitter-logo.png"]autorelease];
NSString *imagepath = [[NSBundle mainBundle] pathForResource:#"twitter-logo" ofType:#"png"];
UIImage *image =[[ UIImage alloc] initWithContentsOfFile:imagepath];
cell.imageView.image = image;
cell.detailTextLabel.text= #"Add Subtitle here";
Tweet *currentTweet = [[xmlParser tweets] objectAtIndex:indexPath.row];
if(indexPath.row<pageSize)
{
cell.textLabel.text = currentTweet.content;
}
else
{
cell.textLabel.text = #"Load more ";
}
NSLog(#"cell: %#",cell);
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(IBAction)loadmorebutton:(id)sender;
{
NSIndexPath *currentPath = [self.tableView indexPathForSelectedRow];
NSIndexPath *nextPath = [NSIndexPath indexPathForRow:currentPath.row+1 inSection:currentPath.section];
[self.tableView selectRowAtIndexPath:nextPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row==pageSize)
{
pageSize=pageSize+2;
[tableView reloadData];
}
}
/*
-(IBAction)pagecontrol:(UIPageControl *)pageControl
{
[self.tableView reloadData];
}
-(IBAction)Pageindexchanges:(id)sender
{
NSLog(#"clicked page index: %i ",pagecontrol.currentPage);
}
*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 55;
}
#pragma mark -
#pragma mark Table view delegate
/*- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
*/
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
}
- (void)dealloc
{
[xmlParser release];
[super dealloc];
}
#end
Try this code may be helped you...
Add the spinner directly to the cell view felt a little hacky, so I used a 1x1 transparent png as the image view and resized it to be whatever my spinner size is:
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"NoReuse"] autorelease];
cell.textLabel.text = #"Loading...";
UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
// Spacer is a 1x1 transparent png
UIImage *spacer = [UIImage imageNamed:#"spacer"];
UIGraphicsBeginImageContext(spinner.frame.size);
[spacer drawInRect:CGRectMake(0,0,spinner.frame.size.width,spinner.frame.size.height)];
UIImage* resizedSpacer = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = resizedSpacer;
[cell.imageView addSubview:spinner];
[spinner startAnimating];
return cell;
That gives a cell that looks like this:
This May Help you
https://github.com/pothibo/PHRefreshTriggerView
And second one option is
https://github.com/enormego/EGOTableViewPullRefresh
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pass data to detail view after being selected in a table view?
I'm using a plist (array of dictionaries) to populate a tableview. Now, when a cell i pressed, I want to pass the reprecented dictionary to the detail view with a segue. It's working properly to fill the tableview, but how do I send the same value to the detail view? This is my try:
#import "WinesViewController.h"
#import "WineObject.h"
#import "WineCell.h"
#import "WinesDetailViewController.h"
#interface WinesViewController ()
#end
#implementation WinesViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (void)viewWillAppear:(BOOL)animated {
wine = [[WineObject alloc] initWithLibraryName:#"Wine"];
self.title = #"Vinene";
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
- (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 [wine libraryCount];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"wineCell";
WineCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
cell.nameLabel.text = [[wine libraryItemAtIndex:indexPath.row] valueForKey:#"Name"];
cell.districtLabel.text = [[wine libraryItemAtIndex:indexPath.row] valueForKey:#"District"];
cell.countryLabel.text = [[wine libraryItemAtIndex:indexPath.row] valueForKey:#"Country"];
cell.bottleImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:#"Image"]];
cell.flagImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:#"Flag"]];
cell.fyldeImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:#"Fylde"]];
cell.friskhetImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:#"Friskhet"]];
cell.garvesyreImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:#"Garvesyre"]];
return cell;
}
#pragma mark - Table view delegate
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"DetailSegue"]) {
NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
WinesDetailViewController *winesdetailViewController = [segue destinationViewController];
//Here comes the error line:
winesdetailViewController.winedetailName = [wine objectAtIndex:indexPath.row] valueForKey:#"Name"];
}
}
I get one error for:
winesdetailViewController.winedetailName = [wine objectAtIndex:indexPath.row] valueForKey:#"Name"];
Use of undeclaired identifier: indexPath. did you mean NSIndexPath? I think I've missed something important here..
Instead of indexPath.row (which doesn't exist in this function like it does in your tableView:cellForRowAtIndexPath: function where it is passed as an argument) use selectedRowIndex like this:
winesdetailViewController.winedetailName = [wine objectAtIndex:selectedRowIndex.row] valueForKey:#"Name"];
Or, even better yet, change your detail view controller to just accept the whole dictionary, pass the dictionary, and let it set its' own values:
winesdetailViewController.winedetail = [wine objectAtIndex:selectedRowIndex.row];
The error is correct, there is no variable indexPath defined there. However, just a couple lines above that line you define selectedRowIndex which probably has the value that you're after.
How can I adapt this to be able to make multiple selections? and get the selected ones
- (id)initWithCellIdentifier:(NSString *)cellID {
if ((self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID])) {
UITableViewCell *cell=self;
UIImage *cry = [UIImage APP_CRYSTAL_SELECT];
self.leftImage = [[[UIImageView alloc] initWithImage:cry] autorelease] ;
[self.contentView addSubview:leftImage];
}
And the selected method is:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
if(selected)
{
NSArray *subviews=[self.contentView subviews];
for(UIView* view in subviews){
if([view isEqual:self.leftImage]){
[self.leftImage setHighlightedImage:[UIImage APP_CRYSTAL_SELECTED]];
}
}
}
else
{
NSArray *subviews=[self.contentView subviews];
for(UIView* view in subviews){
if([view isEqual:self.leftImage]){
[self.leftImage setHighlightedImage:[UIImage APP_CRYSTAL_SELECT]];
}
}
}
}
For multiple selection, setup an NSMutableArray ivar (selectedIndexPaths in this case) to hold the items that are selected. In didSelectRowAtIndexPath add or remove indexPaths to this array.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(![self.selectedIndexPaths containsObject:indexPath])
[self.selectedIndexPaths addObject:indexPath];
else
[self.selectedIndexPaths removeObject:indexPath];
}
Use selectedIndexPaths later to do whatever you wish! Cheers!
-Akshay
I have a table view that you can add and delete cells. I can enter multiple cells and when i go to the next page and then switch back, all of my entries/ cells are erased. Can any one figure this out? Here is my code:
#implementation FacePlatesViewController
#synthesize woodGrain;
#synthesize nav, array;
#synthesize EditButton;
#synthesize myTableView, image;
#synthesize cell, string1;
#synthesize myDic, cells, defaults;
#synthesize selectedCell, currentChosenFund;
- (void)viewDidLoad {
[super viewDidLoad];
NSString * myFile = [[NSBundle mainBundle]pathForResource:#"cells" ofType:#"plist"];
self.myTableView.backgroundColor = [UIColor clearColor];
cells = [[NSMutableArray alloc]initWithContentsOfFile:myFile];
}
- (void)addObject:(id)anObject
{
if (anObject != nil)
{
[cells addObject:anObject];
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.myTableView reloadData];
}
- (IBAction)editButton:(id)sender
{
if (self.editing)
{
[self setEditing:NO animated:YES];
[self.myTableView setEditing:NO animated:YES];
}
else
{
[self setEditing:YES animated:YES];
[self.myTableView setEditing:YES animated:YES];
}
}
- (void)add
{
MyDetailViewController * detail = [[MyDetailViewController alloc]init];
detail.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:detail animated:YES];
[detail.text becomeFirstResponder];
[detail release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [cells count];
}
- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[[self cells] removeObjectAtIndex:[indexPath row]];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
[[self myTableView] deleteRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier] autorelease];
}
//The if block should end here. You should set the cell's label irrespective whether the cell was nil. This is the cause of the issue you are facing.
cell.textLabel.text = [[cells objectAtIndex:indexPath.row] valueForKey:#"name"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FirstFolderViewController * first = [[FirstFolderViewController alloc]init];
first.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:first animated:YES];
[first release];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)targetIndexPath
{
NSUInteger sourceIndex = [sourceIndexPath row];
NSUInteger targetIndex = [targetIndexPath row];
if (sourceIndex != targetIndex)
{
[[self cells] exchangeObjectAtIndex:sourceIndex
withObjectAtIndex:targetIndex];
}
}
- (void)dealloc
{
[woodGrain release];
[myTableView release];
[EditButton release];
[nav release];
[cells release];
[myTableView release];
[myDic release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[self setWoodGrain:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Thanks :D
Actually even unloading of the view will be enough to throw away the cells. Try this in your viewDidLoad:
if(!cells) {
NSString * myFile = [[NSBundle mainBundle]pathForResource:#"cells" ofType:#"plist"];
self.myTableView.backgroundColor = [UIColor clearColor];
cells = [[NSMutableArray alloc]initWithContentsOfFile:myFile];
}
(this way you won't be rereading the array every time the view is loaded).
And if you want the added cells to persist between app restarts, you do need to save them somewhere. You can't change the files in the main bundle, but you can write your own file into the Caches folder, which you can get via:
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
Write your file into that folder and read the cells from there instead of the main bundle. If you have some pre-defined cells in the main bundle file, you can check if the file in the Caches folder exists when the app starts, and if not, copy the bundle's file into the Caches folder.
Edit: if you do presentModalViewController to get back from the another page, you'll get a fresh copy of FacePlatesViewController, which obviously loads the default cells from the file.
Instead, you should add a "delegate" property to your FirstFolderViewController:
#property(nonatomic, assign) id delegate; //yes, assign, not retain
then when presenting FirstFolderViewController do:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FirstFolderViewController * first = [[FirstFolderViewController alloc]init];
first.delegate = self;
first.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:first animated:YES];
[first release];
}
Then add a method to FacePlatesViewController:
- (void) onDoneWithFirstFolderViewController //you can come up with a better name
{
[self dismissModalViewControllerAnimated:YES];
}
and in your FirstFolderViewController, when you are ready to close it, do:
if([delegate respondsToSelector:#selector(onDoneWithFirstFolderViewController)])
[delegate onDoneWithFirstFolderViewController];
Ironically, if you had implemented the cell persistence in a file, this issue might have been unnoticed (because each new FacePlatesViewController would load an up-to-date cell list), but you would have had a memory leak each time you went between pages.
To me, the problem seems to be related to your code in ViewWillAppear: Have you ensured that your cells array is fine when you call [self.myTableView reloadData]; ?
Also, I noticed myTableView. Are you subclassing UITableViewController or implementing table delegates? If you are subclassing, the table view reference is named tableView.
HTH,
Akshay