Search Controller issue - ios

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath**
{
static NSString *CellIdentifier = #"TableCell";
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];**
// Configure the cell...
int row = [indexPath row];
cell.TitleLabel.text = _Title[row];
cell.DescriptionLabel.text = _Description[row];
cell.FeeSchedule.text = _Fschedule[row];
cell.NonFS.text = _Nonfeeschedule[row];
cell.ThumbImage.image = [UIImage imageNamed:_Images[row]];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [medicalCodes objectAtIndex:indexPath.row];
return cell;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [medicalCodes objectAtIndex:indexPath.row];
}
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([[segue identifier] isEqualToString:#"ShowDetails"]) {
DetailViewController *detailviewcontroller = [segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
int row = [myIndexPath row];
detailviewcontroller.DetailModal = #[_Title[row],_Description[row],_Fschedule[row],_Nonfeeschedule[row],_Images[row]];
}
}
`enter code here`- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
searchResults = [medicalCodes filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
I have a problem, I am trying to get my search bar to work, however it is stoping at this point right here essentially causing the app to crash. I am open to any suggestions as to any ways to add a search bar better. Any suggestions on what I can do? Any help is appreciated.

if you are update your data in main thread
or
if you are reload your tableview update with UI Main thread
dispatch_async(dispatch_get_main_queue(), ^(void){
[self.tableView reloadData]
});

Looking through your code here, you are configuring cell even before allocating it.
And the codes you've written after following line will go untouched since you are returning the call.
cell.textLabel.text = [medicalCodes objectAtIndex:indexPath.row];
return cell;
I'm not sure what you are trying to achieve in -tableView:cellForRowAtIndexPath:. But I would suggest you try this,
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"TableCell";
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
//you can also allocate your custom cell here and then configure it as your need.
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
int row = [indexPath row];
cell.TitleLabel.text = _Title[row];
cell.DescriptionLabel.text = _Description[row];
cell.FeeSchedule.text = _Fschedule[row];
cell.NonFS.text = _Nonfeeschedule[row];
cell.ThumbImage.image = [UIImage imageNamed:_Images[row]];
cell.textLabel.text = medicalCodes[indexPath.row];
return cell;
}

Related

Deselect a row of tableview search results

I have a table view which list countries and I can select multiple raws. I've the option of select and deselect raws. The problem comes when I add a Search bar, I can`t deselect a raw of the results list because the method "didDeselectRowAtIndexPath" is never called when I press a results item.
I searched about this problem but nothing,
Thanks in advance,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
//[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:indexPath.row];
UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
tableViewCell.accessoryView.hidden = NO;
tableViewCell.accessoryType = UITableViewCellAccessoryCheckmark;
NSDictionary *country = [self.searchResult objectAtIndex:indexPath.row];
[self.selectedItems addObject: country];
}
else
{
//[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:indexPath.row];
UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
tableViewCell.accessoryView.hidden = NO;
tableViewCell.accessoryType = UITableViewCellAccessoryCheckmark;
NSDictionary *country = [self.countriesArray objectAtIndex:indexPath.row];
[self.selectedItems addObject: country];
}
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
//[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
tableViewCell.accessoryView.hidden = YES;
tableViewCell.accessoryType = UITableViewCellAccessoryNone;
NSDictionary *country = [self.searchResult objectAtIndex:indexPath.row];
[self.selectedItems removeObject:country];
}else
{
//[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
tableViewCell.accessoryView.hidden = YES;
tableViewCell.accessoryType = UITableViewCellAccessoryNone;
NSDictionary *country = [self.countriesArray objectAtIndex:indexPath.row];
[self.selectedItems removeObject:country];
}
}

How to code PrepareForSeque in UITableView that has sections and searching

I have constructed a nice TableView that contains sections, searching, and the alphabetical strip on the right.
I tested it and all seemed well until I noticed that anything after the "A"s was not working correctly. I discovered the reason - in my PrepareForSegue I was passing the object I found at the row, but not paying any attention to the sections.
I searched stack overflow and found some things like I am trying to do, but it seems they are coding in the didSelectRowAtIndexPath, no prepare for segue. And I was unable to get any of the code to work.
My first question is what is the relationship between the two methods? I am using Storyboards so I think I should stick with the segues. But then how do I find out which employee object to pass?
Any help would be greatly appreciated.
Bryan
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
employee *dtlEmployee = [_employees objectAtIndex:indexPath.row];
self.detailViewController.detailItem = dtlEmployee;
}
else
{
// employee *dtlEmployee;
//
// int row = indexPath.row;
// int section = indexPath.section;
//
// NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
//
// [self.tableView deselectRowAtIndexPath:newIndexPath animated:NO];
// UITableViewCell *cell = [tableView cellForRowAtIndexPath:newIndexPath];
//
// dtlEmployee = [_employees objectAtIndex:newIndexPath];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
employee *dtlEmployee;
// int row = [[self.tableView] indexPath.row];
// int section = [self.tableView indexPath.section];
// NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
// dtlEmployee = [_employees objectAtIndex:newIndexPath];
// NSIndexPath *selectedRowIndexPath = [self.tableView indexPathForSelectedRow];
// NSUInteger selectedRow = selectedRowIndexPath.row;
// NSUInteger selectedSection = selectedRowIndexPath.section;
// NSArray *tmpArray = [_employees objectAtIndex:[self.tableView indexPathForSelectedRow]];
// dtlEmployee = [tmpArray objectAtIndex:selectedRowIndexPath.row];
// dtlEmployee = [tmpArray objectAtIndex:indexPath.row];
//
// dtlEmployee = [_employees objectAtIndex:selectedRowIndexPath.]
//
if (isSearching)
{
dtlEmployee = [self.filteredEmployees objectAtIndex:self.searchDisplayController.searchResultsTableView.indexPathForSelectedRow.row];
}
else
{
dtlEmployee = [_employees objectAtIndex:[self.tableView indexPathForSelectedRow].row];
}
[[segue destinationViewController] setDetailItem:dtlEmployee];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self.tableView dequeueReusableCellWithIdentifier: CellIdentifier];
//cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (isSearching)
{employee *thisEmployee = [self.filteredEmployees objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;}
else
{employee *thisEmployee = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;}
return cell;
}
Assuming that your segue is connected to the table view cell, your sender in prepareForSegue: is actually a cell. (Use logging or the debugger to be sure.)
That means you can ask your table view for an index path that matches the cell and use the same logic that you would have in tableView:cellForRowAtIndexPath: for obtaining an object from a path.
Your logic for getting the right employee in tableView:cellForRowAtIndexPath: looks like this:
if (isSearching)
{
employee *thisEmployee = [self.filteredEmployees objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;
}
else
{
employee *thisEmployee = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;
}
But your logic in prepareForSegue:sender: looks like this:
if (isSearching)
{
dtlEmployee = [self.filteredEmployees objectAtIndex:self.searchDisplayController.searchResultsTableView.indexPathForSelectedRow.row];
}
else
{
dtlEmployee = [_employees objectAtIndex:[self.tableView indexPathForSelectedRow].row];
}
You need to make the logic when performing the segue match the one when populating the cell, which from the sound of it works correctly. It appears that you're doing it correctly when isSearching is true, so when it's not true, the following line should be used:
employee *thisEmployee = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex: [self.tableView indexPathForSelectedRow].section]] objectAtIndex: [self.tableView indexPathForSelectedRow].row];

How to add a search bar and search display to an rss feed in UItableview

I created an RSS reader that parses from a .xml file. I am trying to create a search bar and search display controller, but am not sure how to search the objectForKey "title" or objectForKey "summary" within the UITableView.
Any help would be greatly appreciated.
The numberOfRowsInSection and cellForRowAtIndexPath looked like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
I recently tried to follow this sample project - https://github.com/deepthit/TableViewSearch.git - based on a suggestion.
My code then looked like this:
#interface QldRecentJudgmentsViewController () {
__strong NSArray *mFilteredArray_;
__strong UISearchBar *mSearchBar_;
__strong UISearchDisplayController *mSearchDisplayController_;
}
#end
#implementation ViewController
#synthesize parseResults = _parseResults, HUD;
- (void)viewDidLoad {
[super viewDidLoad];
mSearchBar_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0,
0,
self.view.bounds.size.width,
44)];
mSearchBar_.delegate = self;
mSearchBar_.placeholder = #"search";
self.tableView.tableHeaderView = mSearchBar_;
mSearchDisplayController_ = [[UISearchDisplayController alloc] initWithSearchBar:mSearchBar_
contentsController:self];
mSearchDisplayController_.searchResultsDelegate = self;
mSearchDisplayController_.searchResultsDataSource = self;
mSearchDisplayController_.delegate = self;
}
#pragma mark - Table view data source
- (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 self.parseResults.count;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
return [mFilteredArray_ count];
}
return parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id result;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
result = [mFilteredArray_ objectAtIndex:indexPath.row];
}
else
{
result = [parseResults objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *url = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"link"];
NSString *title = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
WebViewController *viewController = [[WebViewController alloc] initWithURL:url title:title];
[self.navigationController pushViewController:viewController animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText {
if ([searchText length] == 0)
{
[self.tableView reloadData];
return;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.title contains[cd] %# OR SELF.summary contains[cd] %#", searchText, searchText];
mFilteredArray_ = [self.parseResults filteredArrayUsingPredicate:predicate];
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
mFilteredArray_ = nil;
[self.tableView reloadData];
}
However, when I follow this the RSS feed does not load anymore in the tableview, so there are no results. Nevertheless when I try to search it does not correctly search the "title" or "summary" and the search results do not appear correctly -the cells are not neatly aligned after searching for something and getting results. Also, the only way to see RSS in the tableview is to search for any generic string, but once you press cancel in the search bar the RSS feed disappears and shows an empty tableview.
Thanks for any help in advance.

UISearchcontroller is not working correctly

I have implemented the search functionality as below. I am able to retrieve the rows based on search string but they are empty, when i click on the empty search result cell am able to navigate correctly for each search result.I am using story board configured cells to display the table. I mean am using tags in order to populate the data and the images.
- (void)viewDidLoad
{
sqlDatabase = [SQLiteDatabase getDatabaseInstance];
filteredItemist=[[NSMutableArray alloc] initWithArray:[sqlDatabase fetchCropListBySoilName:soilName]];
[super viewDidLoad];
}
- (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] ;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell...
Crop * crop = [filteredItemist objectAtIndex:[indexPath row]];
NSString* str = [NSString stringWithFormat:#"%#.jpg",crop.cropName.lowercaseString];
UIImageView *cropImageView = (UIImageView *)[cell viewWithTag:100];
cropImageView.image = [UIImage imageNamed:str];
UILabel *cropNameLabel = (UILabel *)[cell viewWithTag:70];
cropNameLabel.text = [crop cropName];
return cell;
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationItem.title = #"Item List";
filteredItemist = [[NSMutableArray alloc]initWithArray:[sqlDatabase fetchCropListBySoilName:soilName]];
[self.tableView reloadData];
self.navigationController.toolbarHidden = YES;
[super viewWillAppear:animated];
}
- (void)filterContentForSearchText:(NSString*)searchText
{
if([searchText length] == 0)
{
isFiltered = FALSE;
[filteredItemist removeAllObjects];
[filteredItemist addObjectsFromArray:[sqlDatabase fetchCropListBySoilName:soilName]];
}
else{
isFiltered = TRUE;
[filteredItemist removeAllObjects];
for(Crop *i in [sqlDatabase fetchCropListBySoilName:soilName]){
NSRange stringRange = [[i cropName]rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[filteredItemist addObject:i];
}
}
}
[self.tableView reloadData];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString];
return YES;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.searchBar resignFirstResponder];
}
Edit :
after changing the code to self.tableview :
Instead of this :
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
use this :
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Search results displayed in a separate table view. So if you use tableView without self you may be referring search results table view.

iOS: Tableview multiple selection - AccessoryCheckmark checking reusable cells

I'm using a tableview with sections and multiple selection, but I have an issue with multiple rows being checked when one row is chosen...
I've seen a few other threads about this, but didn't really get a solution...
Here's my code:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath
{
[employeeTable deselectRowAtIndexPath:[employeeTable indexPathForSelectedRow] animated:NO];
UITableViewCell *cell = [employeeTable cellForRowAtIndexPath:indexPath];
// get the letter in each section
NSString *alphabet = [charIndex objectAtIndex:indexPath.section];
// get the names beginning with the letter
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", alphabet];
NSArray *names = [listOfNames filteredArrayUsingPredicate:predicate];
NSString *name = [names objectAtIndex:indexPath.row];
for(int i = 0; i < [employeeConnection.employees count]; i++)
{
Employee *aEmployee = [employeeConnection.employees objectAtIndex:i];
NSString *firstName = aEmployee.firstName;
NSString *lastName = aEmployee.lastName;
NSString *fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
if([fullName isEqualToString:name])
{
NSLog(#"Name: %#", name);
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// Reflect selection in data model
[chosenEmployees addObject:aEmployee.employeeID];
[chosenEmployeesNames addObject:name];
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
// Reflect deselection in data model
[chosenEmployees removeObject:aEmployee.employeeID];
[chosenEmployeesNames removeObject:name];
}
}
}
}
Update: Added cellForRowAtIndexPath
- (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];
cell.textLabel.textColor = [UIColor whiteColor];
}
// Get the letter in the current section
NSString *alphabet = [charIndex objectAtIndex:[indexPath section]];
// Get the names beginning with the letter
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", alphabet];
NSArray *names = [listOfNames filteredArrayUsingPredicate:predicate];
if([names count] > 0)
{
// Extract the name
cell.textLabel.text = [names objectAtIndex:indexPath.row];
}
return cell;
}
I would suggest storing an NSMutableSet of either the checked ManagedObject (when using CoreData) or simply the checked IndexPaths. In -cellForRowAtIndexPath: you can then check if the cell is supposed to be checked.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *const identifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
cell.textLabel.textColor = UIColor.whiteColor;
}
if ([self.checkedIndexPaths containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *const cell = [tableView cellForRowAtIndexPath:indexPath];
[table deselectRowAtIndexPath:indexPath animated:NO];
if ([self.checkedIndexPaths containsObject:indexPath]) {
[self.checkedIndexPaths removeObject:indexPath];
cell.accessoryType = UITableViewCellAccessoryNone;
}
else {
[self.checkedIndexPaths addObject:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
Since cells are being reused, you need to set the accessory mark to on or off for every cell in the table in the cellForRowAtInexPath table datasource method.
So the cell.accessoryType cell property should be soecified in the cellForRowAtInexPath and not the didSelectRow delegate method.
In the didSelectRow, just keep track of the selected rows in an array, and set the cells accessory mark to none or checkmark in the cellForRowAtInexPath dependingon the array value.

Resources