Really need help. I've looked everywhere but still i cant find an answer. So, when i scroll my UITableView with custom cells in it its recreating cell each time I see it. As the result it lowers my performance significantly.
my method
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellWithViewForProduct";
ProductCell *cell = (ProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
ProductDataStruct *dataStruct = [self.arrayData objectAtIndex:indexPath.row];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"productCell" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[ProductCell class]])
{
cell = (ProductCell *)currentObject;
break;
}
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.roundingIncrement = [NSNumber numberWithDouble:0.01];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *price = [formatter stringFromNumber:[NSNumber numberWithFloat:(dataStruct.price.floatValue * [[[NSUserDefaults standardUserDefaults] objectForKey:#"CurrencyCoefficient"] floatValue])]];
NSString *priceString = [NSString stringWithFormat:#"%# %#", price, [[NSUserDefaults standardUserDefaults] objectForKey:#"Currency"]];
cell.productPrice.text = priceString;
cell.productDescription.text = [NSString stringWithFormat:#"%#", dataStruct.descriptionText];
cell.productTitle.text = [NSString stringWithFormat:#"%#", dataStruct.title];
if (dataStruct.hit.integerValue == 1)
{
[cell.productImage.layer addSublayer:[hitView layer]];
}
else
if (dataStruct.hit.integerValue == 2)
[cell.productImage.layer addSublayer:[newsItemView layer]];
if (!dataStruct.image)
{
if (self.tableView.dragging == NO && self.tableView.decelerating == NO && dataStruct.link)
{
[self startIconDownload:dataStruct forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
//cell.productImage.image = [UIImage imageNamed:#"Placeholder.png"];
// if a download is deferred or in progress, return a loading screen
cell.productImage.alpha = 0;
[cell.productImageLoadingIndocator startAnimating];
}
else
{
if (self.didLoad)
{
cell.productImage.alpha = 0;
}
[cell.productImageLoadingIndocator stopAnimating];
cell.productImage.image = dataStruct.image;
[self imageAnimation: cell.productImage];
}
NSLog(#"WAZAAA");
return cell;
}
This entire chunk of code:
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"productCell" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[ProductCell class]])
{
cell = (ProductCell *)currentObject;
break;
}
}
seems wrong to me. Above it,
ProductCell *cell = (ProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
should be sufficient to get you a cell to use.
first create a #property (nonatomic, assign) IBOutlet ProductCell *prodCell; in the .h
Then in the .m you just need this
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellWithViewForProduct";
ProductCell *cell = (ProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"productCell" owner:self options:nil];
cell = prodCell;
self.prodCell = nil;
NSLog(#"WAZAAA"); //Now it will only be called when a new cell is created.
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.roundingIncrement = [NSNumber numberWithDouble:0.01];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *price = [formatter stringFromNumber:[NSNumber numberWithFloat:(dataStruct.price.floatValue * [[[NSUserDefaults standardUserDefaults] objectForKey:#"CurrencyCoefficient"] floatValue])]];
NSString *priceString = [NSString stringWithFormat:#"%# %#", price, [[NSUserDefaults standardUserDefaults] objectForKey:#"Currency"]];
cell.productPrice.text = priceString;
cell.productDescription.text = [NSString stringWithFormat:#"%#", dataStruct.descriptionText];
cell.productTitle.text = [NSString stringWithFormat:#"%#", dataStruct.title];
if (dataStruct.hit.integerValue == 1)
{
[cell.productImage.layer addSublayer:[hitView layer]];
}
else
if (dataStruct.hit.integerValue == 2)
[cell.productImage.layer addSublayer:[newsItemView layer]];
if (!dataStruct.image)
{
if (self.tableView.dragging == NO && self.tableView.decelerating == NO && dataStruct.link)
{
[self startIconDownload:dataStruct forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
//cell.productImage.image = [UIImage imageNamed:#"Placeholder.png"];
// if a download is deferred or in progress, return a loading screen
cell.productImage.alpha = 0;
[cell.productImageLoadingIndocator startAnimating];
}
else
{
if (self.didLoad)
{
cell.productImage.alpha = 0;
}
[cell.productImageLoadingIndocator stopAnimating];
cell.productImage.image = dataStruct.image;
[self imageAnimation: cell.productImage];
}
NSLog(#"WAZAAA"); //Here doesn't make any sense, the cell is returned for being displayed, this doesn't mean it's being created.
return cell;
}
Related
Needless to say, i am a novice. I am trying to add images and text to a UITableView. I have been able to add the text but I am having problems with adding different images to the desired text.
I have 2 separate PHP codes for 1 database:
The first gets the text and an id for the image assigned to the text (imageID)
The second uses the id (from the first PHP) to acquire the image
My code is fine but currently only 1 image is appearing for all the text
My question is how do I assign each image to their text ?
And how do I not assign an image to the text that do not have images as some of the texts don't have images with them?
My code is as follows:
Connection and data download:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *list = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
jsonArray = [NSJSONSerialization JSONObjectWithData:downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
jsonElement = jsonArray[i];
// Create a new cell object and set its props to JsonElement properties
if (![jsonElement [#"Thought"] isEqual:[NSNull null]])
{
NSString *listText =jsonElement [#"Thought"];
if ([listText length] > 0)
{
NSString *cellText = jsonElement[#"Thought"];
[list addObject:cellText];
NSLog(#"list Cell: %#", cellText);
}
if (![jsonElement [#"filename"] isEqual:[NSNull null]])
{
imageID = jsonElement[#"id"];
}
NSLog(#"Cell Image: %#", imageID);
}
}
[[self tableView1] reloadData];
}
Cells in the table:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleIdentifier = #"SimpleIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleIdentifier];
}
cell.textLabel.text = [list objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont italicSystemFontOfSize:20];
if ([imageID length] > 0)
{
urlStr = [NSString stringWithFormat:#"http://database.name/getimage.php?id=%#", imageID];
NSURL *imageUrl = [NSURL URLWithString:urlStr];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = imageLoad;
}
return cell;
}
You should not leave any case untouched in tableview:cellForRowAtIndexPath. What happens when you try this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleIdentifier = #"SimpleIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleIdentifier];
}
cell.textLabel.text = [list objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont italicSystemFontOfSize:20];
if ([imageID length] > 0)
{
urlStr = [NSString stringWithFormat:#"http://database.name/getimage.php?id=%#", imageID];
NSURL *imageUrl = [NSURL URLWithString:urlStr];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = imageLoad;
}
else //I assume this is the case when a row does not contain an image right?
{
cell.imageView.image = nil; //Or the below line for better aestethics
//cell.imageView.image = [UIImage imageNamed:#"placeholderimage.png"];
}
return cell;
}
By the way NSData *imageData = [NSData dataWithContentsOfURL:imageUrl]; is called everytime tableview:cellForRowAtIndexPath is triggered and this happens alot. As far as I know dataWithContentsOfURL: is a heavy process and stalls the UI until it downloads the image. So it would be better to download one specific image once and save it in a NSMutableArray or NSMutableDictionary. For instance:
//in your .m
#interface ViewController ()
#property NSMutableDictionary * imageIdDictionary;
#end
#implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
imageIdDictionary = [[NSMutableDictionary alloc] init];
}
And change your tableView:cellForRowAtIndexPath: to:
//Added this. You need a second array just like `list` which has all the different imageID's stored
imageID = [list2 objectAtIndex:indexPath.row];
if ([imageID length] > 0) {
if([self.imageIdDictionary objectForKey:imageID]) {
cell.imageView.image = [self.imageIdDictionary objectForKey:imageID];
}
else {
urlStr = [NSString stringWithFormat:#"http://database.name/getimage.php?id=%#", imageID];
NSURL *imageUrl = [NSURL URLWithString:urlStr];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = imageLoad;
[self.imageIdDictionary setValue:imageLoad forKey:imageID];
//added these two lines!!!!!!!
NSArray * array = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]];
[table reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
}
}
else {
cell.imageView.image = nil; //Or the below line for better aestethics
//cell.imageView.image = [UIImage imageNamed:#"placeholderimage.png"];
}
This will make your application run much smoother
UITableView's cells are reusable. It means that the cells which are not visible will show the same content before you reset.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleIdentifier = #"SimpleIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleIdentifier];
}
cell.textLabel.text = #"";
cell.imageView.image = nil;
cell.textLabel.text = [list objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont italicSystemFontOfSize:20];
...
}
Just add the reset codes.
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
if (tableView ==tableview1) {
ContactCustom *cell1=(ContactCustom *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell1 == nil) {
[[NSBundle mainBundle] loadNibNamed:#"ContactCustom" owner:self options:nil];
cell1 = contactCustom;
}
NSString *nameStr = [newcontactList objectAtIndex:indexPath.row];
NSArray * arr = [nameStr componentsSeparatedByString:#"!"];
NSLog(#"arr %#\n",arr);
[cell1 ContactNameText:[arr objectAtIndex:0]];
[cell1 MobileNoText:[arr objectAtIndex:1]];
if (![[arr objectAtIndex:3] isEqualToString:#"no"]) {
[cell1 ScreenNameText:[arr objectAtIndex:3]];
}
if (![[arr objectAtIndex:4] isEqualToString:#"0"]) {
[cell1 setImg:[arr objectAtIndex:4]];
}
else
{
cell1.receiveCountBtn.hidden=YES;
}
cell1.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell1.selectionStyle = UITableViewCellSelectionStyleNone;
return cell1;
}
else if (tableView ==tableview2) {
ContactPicsCustom *cell=(ContactPicsCustom *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"ContactPicsCustom" owner:self options:nil];
cell = contactPicsCustom;
}
NSString *nameStr = [sentPicsContactList objectAtIndex:indexPath.row];
NSArray * arr1 = [nameStr componentsSeparatedByString:#"!"];
// NSLog(#"arr1 %#\n",arr1);
User *userObj = [[User alloc]init];
userObj.fName = [arr1 objectAtIndex:0];
userObj.mNo = [arr1 objectAtIndex:1];
// NSLog(#"user %# %#\n",userObj.fName,userObj.mNo);
[cell ContactNameText:[arr1 objectAtIndex:0]];
if ([arr1 count] == 4) {
[cell ScreenNameText:[arr1 objectAtIndex:3]];
}
// [cell setImg:[dicPhotosCount valueForKey:[arr1 objectAtIndex:0]]];
NSInteger cnt = [[DBModel database]photosCnt:userObj];
// NSLog(#"cnt: %d\n",cnt);
if(cnt >= 1)
{
[cell setImg:[NSString stringWithFormat:#"%d",cnt]];
}
else
{
cell.imgView.hidden=YES;
}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
return 0;
}
I have added tabBarController in my project.There is one tabBarItem called ContactsViewController which has tableView with customCell.When I click on the tableViewRow it takes me to next view.then I click someother tabBarItem and again click ContactsViewController i am getting error as UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath.What is wrong with my code?
-(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if (tabBarController.selectedIndex == 0) {
}
else if (tabBarController.selectedIndex == 1) {
UINavigationController *requiredNavigationController = [tabBarController.viewControllers objectAtIndex:1];
[requiredNavigationController popToRootViewControllerAnimated:YES];
}
after i added above method in Appdelegate.m i am getting excepion
Change :
return 0;
To :
return nil;
Table is not getting your custom cell.Check your ContactCustom cell.xib and add your ContactCustom as the class of the cell.
add your custom class name instead of "DeckListCell".
try this:
if (tableView ==tableview1) {
ContactCustom *cell1=(ContactCustom *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *nib;
nib= [[NSBundle mainBundle] loadNibNamed:#"ContactCustom" owner:self options:nil];
for (id oneObject in nib) if ([oneObject isKindOfClass:[ContactCustom class]])
cell = (ContactCustom *)oneObject;
// configure your cell.
}
return cell;
}
i am using tableview and display data. in the table view all checkMark items sent mail. but when scroll the table check marks are unchecked. i don't want un check when scroll the table. please help me. i am developing below code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CustomCellIdentifier = #"CustomCellIdentifier ";
CaptureCell *cell = (CaptureCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CaptureCell"
owner:self options:nil];
for (id oneObject in nib) if ([oneObject isKindOfClass:[CaptureCell class]])
cell = (CaptureCell *)oneObject;
}
if ([[[dataArray objectAtIndex:indexPath.row] objectForKey:#"CaptureId"]isEqualToString:[dict objectForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:#"CaptureId"]]])
{
cell.confirmMail.image = [UIImage imageNamed:#"mailConfirm.png"];
}
NSString *input;
input = [[dataArray objectAtIndex:indexPath.row]objectForKey:#"amount"];
[input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//NSLog(#"after removing white spaces %#",input);
double price;
NSString *numberAsString = nil;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[numberFormatter setLocale:gbLocale];
[gbLocale release];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
if ([[input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]length]!=0)
{
NSLog(#"the input is***** %#",input);
price=[[input stringByReplacingOccurrencesOfString:#"$" withString:#""] doubleValue];
NSLog(#"the price is %f",price);
numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:price]];
NSLog(#"the numberAsString...... %#",numberAsString);
}
[numberFormatter release];
cell.eventNameLbl.text = [[dataArray objectAtIndex:indexPath.row]objectForKey:#"expenseType"];
cell.expenTypeLbl.text = [[dataArray objectAtIndex:indexPath.row]objectForKey:#"empName"];
cell.dataLbl.text = [[dataArray objectAtIndex:indexPath.row]objectForKey:#"Date"];
cell.amountLbl.text = numberAsString;
cell.billImage.image = [UIImage imageWithData:[[dataArray objectAtIndex:indexPath.row]objectForKey:#"image"]];
//[cell.textLabel setText:[NSString stringWithFormat:#"Row %d", indexPath.row]];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
NSIndexPath* selection = [tableView indexPathForSelectedRow];
if (selection && selection.row == indexPath.row) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
// if([[[captureArray objectAtIndex:indexPath.row]objectForKey:#"eventName"]isEqualToString:[[selectedData objectAtIndex:indexPath.row]objectForKey:#"eventName"]])
// NSLog(#"Equal");
//[cell setEditing:YES animated:YES];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *selected = [dataArray objectAtIndex:indexPath.row];
if([tableView isEditing] == YES)
{
AppDelegate *sharedDelegate = [[UIApplication sharedApplication]delegate];
sharedDelegate.isEditCapture = YES;
sharedDelegate.findDate = YES;
NSString *imgDataStr = [[NSString alloc]initWithData:[[dataArray objectAtIndex:indexPath.row]objectForKey:#"image"] encoding:NSUTF8StringEncoding];
NSLog(#"imageStr%#",imgDataStr);
ExpensesCaptureViewController_iPhone *nextController = [[ExpensesCaptureViewController_iPhone alloc] initWithNibName:#"ExpensesCaptureViewController_iPhone" bundle:nil];
nextController.captureId = [[dataArray objectAtIndex:indexPath.row] objectForKey:#"CaptureId"];
[self.navigationController pushViewController:nextController animated:YES];
[imgDataStr release];
[nextController release];
if([selectedData count]>0)
{
[selectedData removeObject:selected];
}
}
else {
if ([[[dataArray objectAtIndex:indexPath.row] objectForKey:#"CaptureId"]isEqualToString:[dict objectForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:#"CaptureId"]]])
{
NSLog(#"sent items");
}
else {
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[selectedData addObject:selected];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[selectedData removeObject:selected];
}
}
}
NSLog(#"DataObjects %d %#",[selectedData count] ,[[dataArray objectAtIndex:indexPath.row] objectForKey:#"eventName"]);
//[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
The problem that you scroll your tableView when - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method is called and you set
NSIndexPath* selection = [tableView indexPathForSelectedRow];
if (selection && selection.row == indexPath.row) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
that means when you will scroll indexPath will be for the current row only so the checkmark at the current row will still checked but the all the other rows will enter the else condition and the checkmark will be removed.
To fix it you should make a do the following:
define the following property:
#property (nonatomic)BOOL isViewIsLoadedForTheFirstTime;
-(void)viewDidLoad
{
self.isViewIsLoadedForTheFirstTime = YES;
}
then replace these lines in the (cellForRow) method
if (selection && selection.row == indexPath.row) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
to the following lines:
if (self.isViewIsLoadedForTheFirstTime) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.isViewIsLoadedForTheFirstTime = NO;
}
This will make you set the check mark only when the view loaded for the first time the when you will scroll it won't change.
I hope that will help you
I am making a small app. And having a trouble right now. Trouble by deleting a table customized cell.
it keep removing the top cell instead of the right selected cell. I delete cell number 20, it still delete the cell number 1. I don't know why. please help me out. Really appreciate.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[sortedArray removeObjectAtIndex:indexPath.row];
[self.tableView reloadData];
}
and here is the array:
- (void)viewDidLoad
{
[super viewDidLoad];
if (detail == nil) {
detail = [[UrlDetail alloc] init];
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
self.arrayData = [NSMutableArray arrayWithContentsOfFile:path];
NSMutableArray *filterArr = [self filterArray];
sortedArray = [[NSMutableArray alloc] initWithArray:filterArr copyItems:YES];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(actionAddNewURL:)] autorelease];
}
and here is the filter function:
-(NSMutableArray *)filterArray
{
NSMutableArray *filterArr = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[filterArr addObject:tempArray];
[tempArray release];
for (NSDictionary *item in arrayData) {
if ([tempArray count]==0)
{
[tempArray addObject:item];
}
else
{
NSDictionary *anItem = [tempArray objectAtIndex:0];
NSString *first = [[anItem objectForKey:#"url"] substringToIndex:1];
NSString *last = [[item objectForKey:#"url"] substringToIndex:1];
if ( [first isEqualToString:last])
{
[tempArray addObject:item];
} else
{
tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:item];
[filterArr addObject:tempArray];
[tempArray release];
}
}
}
// NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:filterArr copyItems:YES];
return filterArr;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if([sortedArray count]>0){
NSLog(#"number of section: %d", [sortedArray count]);
return [sortedArray count];
}
return 0;
}
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section
{
if (isTab) {
if ([self.sortedArray count] > section) {
NSDictionary *dictionary = [[sortedArray objectAtIndex:section] objectAtIndex:0];
NSString *string = [dictionary objectForKey:#"url"];
return [NSString stringWithFormat:#"%#", [[string substringToIndex:1] uppercaseString]];
}
else return nil;
} else
{
return nil;
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = myOwnCell;
}
NSDictionary *dataItem = [[sortedArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.urlName.text = [dataItem objectForKey:#"url"];
cell.titleLabel.text = [dataItem objectForKey:#"title"];
cell.urlName.font = [UIFont italicSystemFontOfSize:14.0];
cell.imageIcon.image = [UIImage imageNamed:[dataItem objectForKey:#"image"]];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Configure the cell.
return cell;
}
Try this one if it works:
- (void) tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSString *key = [[sortedArray allKeys] objectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[sortedArray removeObjectForKey:key];
}
}
I'm having a problem. I have a Custom UITableViewCel, the cell contains a slider which changes a value on a label on the cell. When clicking on the cell and then moving the table, the value replicates itself on another cell and then changes the value to a different cell, resetting it's value to 0.
For demonstration purposes:
First setting the value
Clicking on a random cell then returns:
A totally different cell with the same data that was not put there.
And then when returning back to the cell where the value was first set:
The value is back to 0
Can anyone help me here:
My Slider value changed code;
labelSliderVal.text = [NSString stringWithFormat:#"%1.0f", sliderSlider.value];
if(sliderSlider.value < 30)
{
self.backgroundColor = [UIColor redColor];
}
else if(sliderSlider.value > 60)
{
self.backgroundColor = [UIColor greenColor];
} else {
self.backgroundColor = [UIColor blueColor];
}
And my UITableViews didSelectRowAtIndexPath
Commented out
/*
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}*/
CellForRowAtIndexPath:
- (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"customCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nibObjs = [[NSBundle mainBundle] loadNibNamed:#"CustomCellView" owner:nil options:nil];
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
for(id currentObj in nibObjs)
{
if([currentObj isKindOfClass:[CustomCell class]])
{
cell = (CustomCell *)currentObj;
}
}
}
GradeToolAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
Module *aModule = [appDelegate.modules4 objectAtIndex:indexPath.section];
AssessmentDetail *anAssess = [aModule.assessmentDetails4 objectAtIndex:indexPath.row];
cell.sliderSlider.tag = indexPath.row;
cell.labelAssessment.text = [NSString stringWithFormat:#"%#", anAssess.assessmentName4];
cell.labelAssessmentType.text = [NSString stringWithFormat:#"%#", anAssess.assessmentType4];
cell.labelWeighting.text = [NSString stringWithFormat:#"%#", anAssess.assessmentWeighting4];
cell.labelDueDate.text = [NSString stringWithFormat:#"%#", anAssess.assessmentDueDate4];
return cell;
}
Initialization
NSMutableArray *results = [[NSMutableArray alloc] init];
NSInteger numberOfSections = [myTableView numberOfSections];
for ( int section = 0; section < numberOfSections ; section++ ) {
NSInteger numberOfRows = [myTableView numberOfRowsInSection:section];
NSMutableArray *sectionResults = [NSMutableArray array];
[results addObject:sectionResults];
for ( int row = 0; row < numberOfRows; row++ ) {
[sectionResults addObject:[NSNumber numberWithFloat:0.0]];
}
}
In tableView:cellForRowAtIndexPath:,
...
NSArray *sectionResults = [results objectAtIndex:indexPath.section];
NSNumber *number = [sectionResults objectAtIndex:indexPath.row];
slider.value = [number floatValue];
...
In sliderValueChanged:,
- (void)sliderValueChanged:(UISlider *)slider {
CustomCell *cell = (CustomCell *)slider.superview;
NSIndexPath *indexPath = [myTableView indexPathForCell:cell];
NSArray *sectionResults = [results objectAtIndex:indexPath.section];
...
NSNumber *number = [NSNumber numberWithFloat:slider.value];
cell.sliderValueLabel.text = [NSString stringWithFormat:#"%f", slider.value];
[sectionResults replaceObjectAtIndex:indexPath.row withObject:number];
...
}
Code for totalForSection:,
- (float) totalForSection:(NSInteger)sectionIndex {
NSArray *sectionResults = [results objectAtIndex:sectionIndex];
float result = 0.0;
for (NSNumber *number in sectionResults) {
result += [number floatValue];
}
return result;
}
- (float)sumTotal {
float result = 0.0;
NSinteger numberOfSections = [myTableView numberOfSections];
for ( int i = 0; i < numberOfSections; i++ ) {
result += [self totalForSection:i];
}
return result;
}
Initial Answer
Well this is happening because of reusable cells. You will need to store the state of the contents and update the cell accordingly in tableView:cellForRowAtIndexPath:. On slider value change,
- (void)sliderValueChanged:(UISlider *)slider {
CustomCell *cell = (CustomCell *)slider.superview;
NSIndexPath *indexPath = [myTableView indexPathForCell:cell];
AssessmentDetail *anAssessment = [module.assessmentDetails4 objectAtIndex:indexPath.row];
anAssessment.property = slider.value;
cell.propertyLabel.text = [NSString stringWithFormat:#"%f", slider.value];
}
Now both the model and the label have been changed. So next time cell is reused, the label should get the right value.