didSelectRowAtIndexPath not working for search results - objective-c

I have table view and when I touch cell, detailTextLabel appears. I implemented search, but didSelectRowAtIndexPath doesn't work for search results array. I just copied the code from the cellForRowAtIndexPath.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"name contains[c] %#", searchText];
self.searchResults = [self.cards filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Card Cell" forIndexPath:indexPath];
if (tableView == self.searchDisplayController.searchResultsTableView) {
Card *card = [self.searchResults objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"name"]]];
[cell.detailTextLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"otherSide"]]];
cell.detailTextLabel.hidden = YES;
} else {
Card *card = [self.cards objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"name"]]];
[cell.detailTextLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"otherSide"]]];
cell.detailTextLabel.hidden = YES;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView beginUpdates];
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Card Cell" forIndexPath:indexPath];
if (tableView == self.searchDisplayController.searchResultsTableView) {
Card *card = [self.searchResults objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"name"]]];
[cell.detailTextLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"otherSide"]]];
cell.detailTextLabel.hidden = NO;
} else {
Card *card = [self.cards objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"name"]]];
[cell.detailTextLabel setText:[NSString stringWithFormat:#"%#", [card valueForKey:#"otherSide"]]];
cell.detailTextLabel.hidden = NO;
}
[self.tableView endUpdates];
}

There are some notable differences between cellForRowAtIndexPath and didSelectRowAtIndexPath. cellForRowAtIndexPath creates a cell or gets a existing of the cell stack and you will enter the properties and return it before its displayed. In didSelectRowAtIndexPath you don't get that cell in the parameters, so you have to call the [tableview cellForRowAtIndexPath] instead of [self.tableView dequeueReusableCellWithIdentifier:#"Card Cell" forIndexPath:indexPath]; to get the cell and set the properties.
Also make sure you have set the delegate of the tableview.

Related

How to show UISearchbar bar only in tableview not on UINavigationbar in objective c

I am new in ios and I am facing problem regarding to UISearchbar. I have done code like this
.h
IBOutlet UITableView *table;
NSArray *recipes;
NSArray *searchResults;
.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
recipes = [NSArray arrayWithObjects:#"Egg Benedict", #"Mushroom Risotto", #"Full Breakfast", #"Hamburger", #"Ham and Egg Sandwich", #"Creme Brelee", #"White Chocolate Donut", #"Starbucks Coffee", #"Vegetable Curry", #"Instant Noodle with Egg", #"Noodle with BBQ Pork", #"Japanese Noodle with Pork", #"Green Tea", #"Thai Shrimp Cake", #"Angry Birds Cake", #"Ham and Cheese Panini", nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return [recipes count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
}
return cell;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
But it shows me search bar on navigation bar
But I need to show it on the UItableView itself. Like this in Image
Thanks in advance
I have use code to search from 4 mutable array...
- (void)viewDidLoad {
[super viewDidLoad];
[searchtxt addTarget:self action:#selector(textFieldDidChangeClose:) forControlEvents:UIControlEventEditingChanged];
searchtxt.delegate=self;
}
#pragma mark - Seach Button...
-(void)textFieldDidChangeClose:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
[table reloadData];
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
searchArrayId=[[NSMutableArray alloc] init];
searchArraystatus=[[NSMutableArray alloc] init];
searchArraydescription=[[NSMutableArray alloc] init];
for(NSString *string in idarray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
NSInteger index = [idarray indexOfObject:string];
[searchArraystatus addObject:[shortnamearray objectAtIndex:index]];
[searchArraydescription addObject:[descarray objectAtIndex:index]];
[searchArrayId addObject:[complaintidArray objectAtIndex:index]];
}
}
[table reloadData];
}
}
#pragma mark - TableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFilter)
{
return [searchArray count];
}
else
{
return [idarray count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *STI=#"STI";
IBTClosedComplaintCell *cell = (IBTClosedComplaintCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"IBTClosedComplaintCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType=UITableViewCellAccessoryNone;
}
if(isFilter)
{
cell.Complaintnamelbl.text=[NSString stringWithFormat:#"%#",[searchArray objectAtIndex:indexPath.row]];
cell.statuslbl.text = [NSString stringWithFormat:#"%#",[searchArraystatus objectAtIndex:indexPath.row]];
cell.descriptiolbl.text=[NSString stringWithFormat:#"%#",[searchArraydescription objectAtIndex:indexPath.row]];
cell.complaintidlbl.text = [NSString stringWithFormat:#"%#",[searchArrayId objectAtIndex:indexPath.row]];
}
else
{
cell.Complaintnamelbl.text=[idarray objectAtIndex:indexPath.row];
cell.statuslbl.text=[shortnamearray objectAtIndex:indexPath.row];
cell.descriptiolbl.text=[descarray objectAtIndex:indexPath.row];
cell.complaintidlbl.text=[NSString stringWithFormat:#"%#",[complaintidArray objectAtIndex:indexPath.row]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
IBTClosedNextScreen *next =[[IBTClosedNextScreen alloc] initWithNibName:#"IBTClosedNextScreen" bundle:nil];
[self.navigationController pushViewController:next animated:YES];
if(isFilter)
{
str1=[NSString stringWithFormat:#"%#",[searchArrayId objectAtIndex:indexPath.row]];
NSLog(#"String =%#",str1);
next.str =str1;
}
else
{
str1=[NSString stringWithFormat:#"%#",[self.complaintidArray objectAtIndex:indexPath.row]];
NSLog(#"String =%#",str1);
next.str =str1;
}
}

Selected row changes when scrolling UITableView

currently my situation is my fist row is checked by default. but when i want to uncheck it, it need user to click twice to uncheck it. may i know where i done wrongly?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"Report_SelectGroupTableViewCell";
Report_SelectGroupTableViewCell *cell = (Report_SelectGroupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Report_SelectGroupTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.indexPath = indexPath;
cell.delegate = self;
}
// [myTableView selectRowAtIndexPath:0 animated:NO scrollPosition:UITableViewScrollPositionNone];
//[self tableView:myTableView didSelectRowAtIndexPath:0];
[cell setSelectionStyle:NO];
NSString *groupID = [[groupArray objectAtIndex:indexPath.row] objectForKey:#"group_id"];
if ([groupID isEqualToString:selectedGroup]){
NSMutableDictionary *dict = [groupArray objectAtIndex:indexPath.row];
BOOL isSelected = [[dict objectForKey:#"isSelected"] boolValue];
if (!isSelected) {
isSelected = !isSelected;
[dict setObject:[NSNumber numberWithBool:isSelected] forKey:#"isSelected"];
}
cell.userInteractionEnabled = NO;
}
cell.groupName.text = [[groupArray objectAtIndex:indexPath.row] objectForKey:#"group_name"];
NSMutableDictionary *typeDict = [groupArray objectAtIndex:indexPath.row];
cell.tickButton.selected = [[typeDict objectForKey:#"isSelected"] boolValue];
if (cell.tickButton.selected) {
[cell.tickButton.layer setBorderColor:[UIColor clearColor].CGColor];
if([cell.groupName.text isEqual:#"All Users"])
{
[cell.tickButton setImage:[UIImage imageNamed:#"tick_Icon_empty.png"] forState:UIControlStateNormal];
}
}
else{
[cell.tickButton.layer setBorderColor:[UIColor whiteColor].CGColor];
}
if([cell.groupName.text isEqual:#"All Users"])
{
[cell.tickButton setImage:[UIImage imageNamed:#"tick_Icon.png"] forState:UIControlStateNormal];
[cell.tickButton.layer setBorderColor:[UIColor clearColor].CGColor];
[typeDict setObject:#"1" forKey:#"isSelected"];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Report_SelectGroupTableViewCell *cell = (Report_SelectGroupTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
NSMutableDictionary *dict = [groupArray objectAtIndex:indexPath.row];
BOOL isSelected = [[dict objectForKey:#"isSelected"] boolValue];
isSelected = !isSelected;
[dict setObject:[NSNumber numberWithBool:isSelected] forKey:#"isSelected"];
if (cell.tickButton.isSelected == YES)
{
[cell.tickButton setSelected:NO];
[cell.tickButton.layer setBorderColor:[UIColor whiteColor].CGColor];
if([cell.groupName.text isEqual:#"All Users"])
{
[cell.tickButton setImage:[UIImage imageNamed:#"tick_Icon_empty.png"] forState:UIControlStateNormal];
}
}
else if (cell.tickButton.isSelected == NO)
{
[cell.tickButton setSelected:YES];
[cell.tickButton.layer setBorderColor:[UIColor clearColor].CGColor];
}
}
You should remove
[myTableView selectRowAtIndexPath:0 animated:YES scrollPosition:
UITableViewScrollPositionNone];
and use this to select the first row (this should be called once outside this method or you want to set this row selected everytime each cell is render)
[myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
And I don't know why you called this in this method
[myTableView.delegate tableView:myTableView didSelectRowAtIndexPath:0];
but if you want to call it you should change to this too
[myTableView.delegate tableView:myTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
ps. You should set the cell's selectionStyle correctly to see the cell is selected.
Update::
Try to replace all codes in the method with this
Report_SelectGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Report_SelectGroupTableViewCell"];
if (!cell){
cell = [[[NSBundle mainBundle] loadNibNamed:#"Report_SelectGroupTableViewCell" owner:self options:nil] objectAtIndex:0];
}
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
[tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
return cell;
Please tell me if the first row is not selected and highlighted.

NSPredicate not filtering UITableView?

For some reason NSPredicate isn't filtering my UITableView (it's supposed to be filtering my TableView by selections made in a UIPickerView). Users make their pickerview selections, press the GO button (segue is attached from Pickerview to Table View controller).
Any idea as to why it isn't working? See code below.
ViewController.m (TABLE VIEW CONTROLLER)
- (int)numberOfSectionsInTableView: (UITableView *)tableview
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return [Strains count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strainTableIdentifier = #"StrainTableCell";
StrainTableCell *cell = (StrainTableCell *)[tableView dequeueReusableCellWithIdentifier:strainTableIdentifier];
if (cell == nil)
cell = [[StrainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strainTableIdentifier];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"StrainTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSLog(#"Using the search results");
cell.titleLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.descriptionLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell.ratingLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Rating"];
cell.ailmentLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Ailment"];
cell.actionLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Action"];
cell.ingestLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Ingestion"];
NSLog(#"%#", searchResults);
} else {
NSLog(#"Using the FULL LIST!!");
cell.titleLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.descriptionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell.ratingLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Rating"];
cell.ailmentLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ailment"];
cell.actionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Action"];
cell.ingestLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ingestion"];
}
return cell;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"Title contains[cd] %#",
searchText];
searchResults = [Strains filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
StrainDetailViewController *detailViewController = [[StrainDetailViewController alloc] initWithNibName:#"StrainDetailViewController" bundle:nil]; if ([searchResults count]) {
detailViewController.title = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Title"];
detailViewController.strainDetail = [searchResults objectAtIndex:indexPath.row];
} else {
detailViewController.title = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
detailViewController.strainDetail = [Strains objectAtIndex:indexPath.row];
NSLog(#"%#", Strains);
}
[self.navigationController pushViewController:detailViewController animated:YES];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)PickerViewControllerDidFinish:(PickerViewController *)viewController {
[self.navigationController popViewControllerAnimated:YES];
}
PickerViewController.h
#protocol PickerViewControllerDelegate;
#interface PickerViewController : UIViewController {
UIPickerView *pickerView;
NSMutableArray *array1;
NSMutableArray *array2;
NSMutableArray *array3;
NSArray *Strains;
NSArray *searchResults;
NSMutableData *data;
}
- (IBAction)buttonpressed:(UIButton *)sender;
#property (nonatomic, weak) id<PickerViewControllerDelegate> delegate;
#property (nonatomic, retain) IBOutlet UIPickerView *pickerView;
- (void)populateArray1;
- (void)populateArray2;
- (void)populateArray3;
#end
#protocol PickerViewControllerDelegate <NSObject>
- (void)PickerViewControllerDidFinish:(PickerViewController*)viewController;
#end
PickerViewController.m
#pragma mark -
#pragma mark picker view methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 3;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0)
{
NSLog(#"you selected %#", [array1 objectAtIndex:row]);
}
if (component == 1)
{
NSLog(#"you selected %#", [array2 objectAtIndex:row]);
}
if (component == 2)
{
NSLog(#"you selected %#", [array3 objectAtIndex:row]);
}
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
if (component == 0)
{
return [array1 count];
}
if (component == 1)
{
return [array2 count];
}
if (component == 2)
{
return [array3 count];
}
else
{
return [array1 count];
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
if (component == 0)
{
return [array1 objectAtIndex:row];
}
if (component == 1)
{
return [array2 objectAtIndex:row];
}
if (component == 2)
{
return [array3 objectAtIndex:row];
}
else
{
return [array2 objectAtIndex:row];
}
}
- (void)populateArray1
{
array1 = [[NSMutableArray alloc] init];
[array1 addObject:#"Arthritis"];
[array1 addObject:#"Cancer"];
[array1 addObject:#"HIV"];
[array1 addObject:#"Migraines"];
[array1 addObject:#"Insomnia"];
}
- (void)populateArray2
{
array2 = [[NSMutableArray alloc] init];
[array2 addObject:#"Nausea"];
[array2 addObject:#"Pain"];
[array2 addObject:#"Appetite"];
[array2 addObject:#"Fever"];
[array2 addObject:#"Exhaustion"];
}
- (void)populateArray3
{
array3 = [[NSMutableArray alloc] init];
[array3 addObject:#"Oil"];
[array3 addObject:#"Plant"];
[array3 addObject:#"Edible"];
[array3 addObject:#"Powder"];
}
- (IBAction)buttonpressed:(UIButton *)sender {
NSLog(#"Button Pushed!");
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"pickerGo"])
{
// Get reference to the destination view controller
ViewController *strainTableView = [(UINavigationController *)[segue destinationViewController] topViewController];
NSPredicate *ailmentPredicate = [NSPredicate predicateWithFormat:#"Ailment contains[cd] %#", [pickerView selectedRowInComponent:0]];
NSPredicate *actionPredicate = [NSPredicate predicateWithFormat:#"Action contains[cd] %#", [pickerView selectedRowInComponent:1]];
NSPredicate *ingestPredicate = [NSPredicate predicateWithFormat:#"Ingestion contains[cd] %#", [pickerView selectedRowInComponent:2]];
NSCompoundPredicate *resultPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects: ailmentPredicate,actionPredicate,ingestPredicate, nil]];
searchResults = [Strains filteredArrayUsingPredicate:resultPredicate];
// Pass any objects to the view controller here, like...
[strainTableView setSearchResults: searchResults];
}
}
Very puzzling, your code actually seems ok to me. I'd start by NSLoging searchResults right after the searchResults = [Strains filteredArrayUsingPredicate:resultPredicate]; line is fired, just in case something funny is happening in the table view delegates.
You should also probably check out the free Sensible TableView framework, as it provides automatic searching and filtering for your data. Should save you a ton of time.
It seems your Strains array contains dictionaries. So you should decide on what key you want to filter, for example the Title key, instead of using SELF:
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"Title contains[cd] %#",
searchText];
From the pickerViewController, you need to go back to the tableViewController. You can use delegate. And try to make a separate function in the table view controller to filter which contains the predicate:
- (void)filterContentForPicker:(NSString*)searchText
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"Title contains[cd] %#",
searchText];
searchResults = [Strains filteredArrayUsingPredicate:resultPredicate];
[self.tableView reloadData]
}

Check marks are unchecked when scroll the tableview

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

Deleting and adding rows in uitableview [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
guys, I have tableview, which is loading from my nsarray, but after managing cells, it shows elements in incorrect places.
Generating cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *currentArray = [comments objectAtIndex:indexPath.section];
NSDictionary *currentComment = (NSDictionary *)[currentArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"TitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
int commentLevel = [[currentComment objectForKey:#"level"] intValue];
NSString *commentText = [currentComment objectForKey:#"text"];
cell.textLabel.tag = 0xff ;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Verdana" size:17.0];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.text = commentText;
cell.textLabel.backgroundColor = [UIColor clearColor];
if (commentLevel > 0 && cell.imageView.image == nil) {
cell.imageView.image = [UIImage imageNamed:#"06-arrow-northwest.png"];
}
if (commentLevel == 0 && [[openedSections objectAtIndex:indexPath.section] boolValue] == NO) {
if ([currentArray count] > 1) {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
return cell;
}
Editing method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([[openedSections objectAtIndex:indexPath.section] boolValue] == NO) {
[openedSections replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithInt:1]];
NSMutableArray *rows = [[NSMutableArray alloc] init];
int i = 1;
while (i < [[comments objectAtIndex:indexPath.section] count]) {
NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
[rows addObject:[path copy]];
[path release];
i = i + 1;
}
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
[rows release];
} else if (indexPath.row == 0) {
[openedSections replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithInt:0]];
NSMutableArray *rows = [[NSMutableArray alloc] init];
int i = 1;
while (i < [[comments objectAtIndex:indexPath.section] count]) {
NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
[rows addObject:[path copy]];
[path release];
i = i + 1;
}
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
[rows release];
}
}
Have you any ideas?
You need to update your NSArray whenever you modify the cells in your table, otherwise your data source and view will get out of sync.
So whenever you call:
[tableView insertRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationAutomatic];
You should put
for (NSIndexPath *indexPath in rows)
{
[self.myDataArray insertObject:myRowModel atIndex:indexPath.row];
}
As well so that your view and model stay in sync.
Obviously the above is pseudocode (you'd have to create an instance of whatever your model objects are), and your array will have to be an NSMutableArray or it will crash when you try to insert into it.