Retain UITableView cell state when UISearchBar is used - ios

I am using UISearchBar to search names in UITableView cells. How to retain the cell state when charachters are entered in UISearchBar?
I allocated the checkbox in cellForRowAtIndexPath and suppose I made the selection as shown in the screenshot below.
Now if I start searching with letter 'S', checkBox state is 'unchecked' as can be seen below.
How do I retain the checkBox state even if the cells are "filtered" while searching. I am aware that
cellForRowAtIndexPath is invoked every time when we enter text in UISearchBar.
Below is my cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//static NSString *cellId = #"CheckBoxedCell";
NSString *cellId = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
CheckBoxedCellClass *cell = (CheckBoxedCellClass *)[self.tableViewContact dequeueReusableCellWithIdentifier:cellId];
if(!cell)
{
NSArray *nib;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass" owner:self options:nil];
}
else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass_iPad" owner:self options:nil];
}
for (id object in nib)
{
if([object isKindOfClass:[CheckBoxedCellClass class]])
{
cell = (CheckBoxedCellClass *)object;
break;
}
}
cell = [nib objectAtIndex:0];
}
//handling check box
NSInteger rowNumber = 0;
for(NSInteger i = 0; i < indexPath.section ; i++)
{
rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
SaveCheckBoxedView *saveContact;
if(isFiltered == YES)
{
saveContact = [filterdArray objectAtIndex:indexPath.row];
cell.nameLabel.text = saveContact.nameString;
cell.companyLabel.text = saveContact.companyString;
}
else
{
saveContact = [mutableArray objectAtIndex:indexPath.row];
cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.companyLabel.text = [NSString stringWithFormat:#"%#", [companyArray objectAtIndex:rowNumber]];
}
cell.invIdLabel.text = [NSString stringWithFormat:#"%#", saveContact.invitId];
UIButton *checkBox;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
}
else
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
}
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:event:) forControlEvents:UIControlEventTouchUpInside];
// handle check box view reset when scrolled
if(isFiltered == YES)
{
NSLog(#"filtered");
checkBox.tag = indexPath.row;
BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:#"%d", indexPath.row]] boolValue];
NSLog(#"Row number = %d", indexPath.row);
[checkBox setSelected:buttonPressed];
if(buttonPressed)
{
[checkBox setImage:[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
}
else
{
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
}
}
else
{
BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:#"%d", rowNumber]] boolValue];
NSLog(#"Row number = %d", rowNumber);
[checkBox setSelected:buttonPressed];
if(buttonPressed)
{
[checkBox setImage:[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
}
else
{
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
}
checkBox.tag = rowNumber;
}
[cell.contentView addSubview:checkBox];
return cell;
}
-(void)checkBoxClicked:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableViewContact];
NSIndexPath *indexPath = [self.tableViewContact indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"value of indexPath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);
UIButton *tappedButton = (UIButton*)sender;
NSLog(#"Tag number = %d", [sender tag]);
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"checkBox.png"]])
{
[sender setImage:[UIImage imageNamed: #"checkBoxMarked.png"] forState:UIControlStateNormal];
NSUserDefaults *buttonDefault = [NSUserDefaults standardUserDefaults];
[buttonDefault setBool:YES forKey:#"CHECKMARKEDKEY"];
[self.boolDict setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:#"%d", [sender tag]]];
if(isFiltered == YES)
{
NSString *addId = [filteredArrayOfIds objectAtIndex:indexPath.row];
NSLog(#"filterd id = %#", addId); //get filtered array here
[arrayOfIds addObject:addId];
}
else
{
NSString *finalIntId = [mutableArrayOfIds objectAtIndex:tappedButton.tag];
NSLog(#"Tagged checked button id = %#", finalIntId);
[arrayOfIds addObject:finalIntId];
}
}
else
{
[sender setImage:[UIImage imageNamed:#"checkBox.png"]forState:UIControlStateNormal];
NSLog(#"UnChecked");
[self.boolDict setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:#"%d", [sender tag]]];
if(isFiltered == YES)
{
[arrayOfIds removeObjectIdenticalTo:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
}
else
{
[arrayOfIds removeObjectIdenticalTo:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
}
}
}
And UISearhBar method is as follows
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
searchBar.text=#"";
[searchBar setShowsCancelButton:NO animated:YES];
[searchBar resignFirstResponder];
[self.tableViewContact reloadData];
[self.tableViewContact scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0)
{
isFiltered = NO;
}
else
{
isFiltered = YES;
filterdArray = [[NSMutableArray alloc] init];
filteredArrayOfIds = [[NSMutableArray alloc] init];
for (SaveCheckBoxedView *contact in mutableArray)
{
NSRange nameRange = [contact.nameString rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound)
{
[filterdArray addObject:contact];
[filteredArrayOfIds addObject:contact.invitId];
}
}
}
[self.tableViewContact reloadData];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.mySearchBar resignFirstResponder];
[mySearchBar setShowsCancelButton:NO animated:YES];
}
- (void) searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
[tableViewContact registerClass:[CheckBoxedCellClass class] forCellReuseIdentifier:#"SaveContactCellID"];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filterdArray removeAllObjects];
if(searchString.length > 0)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.mySearchBar.text];
for (NSString *key in arrayOfCharacters)
{
NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate];
[filterdArray addObjectsFromArray:matches];
}
}
return YES;
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
[self.tableViewContact reloadSectionIndexTitles];
}

Solved my own issue with the following code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//static NSString *cellId = #"CheckBoxedCell";
NSString *cellId = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
CheckBoxedCellClass *cell = (CheckBoxedCellClass *)[self.tableViewContact dequeueReusableCellWithIdentifier:cellId];
if(!cell)
{
NSArray *nib;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass" owner:self options:nil];
}
else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass_iPad" owner:self options:nil];
}
for (id object in nib)
{
if([object isKindOfClass:[CheckBoxedCellClass class]])
{
cell = (CheckBoxedCellClass *)object;
break;
}
}
cell = [nib objectAtIndex:0];
}
//set fonts
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:10.0]];
}
else
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:14.0]];
}
//handling check box
NSInteger rowNumber = 0;
for(NSInteger i = 0; i < indexPath.section ; i++)
{
rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
SaveCheckBoxedView *saveContact;
if(isFiltered == YES)
{
saveContact = [filterdArray objectAtIndex:indexPath.row];
cell.nameLabel.text = saveContact.nameString;
cell.companyLabel.text = saveContact.companyString;
}
else
{
saveContact = [mutableArray objectAtIndex:indexPath.row];
cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.companyLabel.text = [NSString stringWithFormat:#"%#", [companyArray objectAtIndex:rowNumber]];
}
cell.invIdLabel.text = [NSString stringWithFormat:#"%#", saveContact.invitId];
UIButton *checkBox;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
}
else
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
}
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:event:) forControlEvents:UIControlEventTouchUpInside];
// handle check box view reset when scrolled
if(isFiltered == YES)
{
NSLog(#"filtered");
BOOL buttonPress = [[boolDictForSearch objectForKey:[filteredArrayOfIds objectAtIndex:indexPath.row]] boolValue];
NSLog(#"button press = %d", buttonPress);
[checkBox setSelected:buttonPress];
if(buttonPress)
{
[checkBox setImage:[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
}
else
{
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
}
checkBox.tag = indexPath.row;
}
else
{
BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:#"%d", rowNumber]] boolValue];
NSLog(#"button pressED = %d", buttonPressed);
NSLog(#"Row number = %d", rowNumber);
[checkBox setSelected:buttonPressed];
if(buttonPressed)
{
[checkBox setImage:[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
}
else
{
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
}
checkBox.tag = rowNumber;
}
[cell.contentView addSubview:checkBox];
return cell;
}
-(void)checkBoxClicked:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableViewContact];
NSIndexPath *indexPath = [self.tableViewContact indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"value of indexPath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);
UIButton *tappedButton = (UIButton*)sender;
NSLog(#"Tag number = %d", [sender tag]);
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"checkBox.png"]])
{
[sender setImage:[UIImage imageNamed: #"checkBoxMarked.png"] forState:UIControlStateNormal];
NSUserDefaults *buttonDefault = [NSUserDefaults standardUserDefaults];
[buttonDefault setBool:YES forKey:#"CHECKMARKEDKEY"];
[self.boolDict setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:#"%d", [sender tag]]];
//[self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:#"%#", saveContact.nameString]];
if(isFiltered == YES)
{
NSString *addId = [filteredArrayOfIds objectAtIndex:indexPath.row];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:addId];
NSLog(#"filterd id = %#", addId); //get filtered array here
[arrayOfIds addObject:addId];
}
else
{
NSString *finalIntId = [mutableArrayOfIds objectAtIndex:tappedButton.tag];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:finalIntId];
NSLog(#"Tagged checked button id = %#", finalIntId);
[arrayOfIds addObject:finalIntId];
}
}
else
{
[sender setImage:[UIImage imageNamed:#"checkBox.png"]forState:UIControlStateNormal];
NSLog(#"UnChecked");
[self.boolDict setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:#"%d", [sender tag]]];
//[self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:#"%#", saveContact.nameString]];
if(isFiltered == YES)
{
[arrayOfIds removeObjectIdenticalTo:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
}
else
{
[arrayOfIds removeObjectIdenticalTo:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
}
}
}

Related

Passing Json Data To Another ViewController Table On Button Click

I am developing an ios app..On Button Click Json Data To Pass Another ViewController...But TableView Not Show Json Data..TableView Show Empty
BBAdsViewController *BBAuthorDetail =[[UIStoryboard storyboardWithName:#"Main" bundle:nil]instantiateViewControllerWithIdentifier:#"AdsViewController"];
[BBAuthorDetail setDelegate:self];
[BBAuthorDetail setSelectionType:BBSelectionAuthorName];
_serverObj = [[Server alloc]init];
[_params setObject:_adDetailsObj.authorDetail forKey:#"author"];
[_serverObj BBAuthorNameWithParams:_params];
[BBAuthorDetail setManagedObjectContext:self.managedObjectContext];
[self.navigationController pushViewController:BBAuthorDetail animated:YES];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"Cell-%li", (long)indexPath.row];
BBAdsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Ad *adObj = (Ad *)[self.adsFilteredArray objectAtIndex:indexPath.row];
if (cell == nil) {
cell = [[BBAdsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.row = indexPath.row;
[cell setDelegate:self];
}
if (![adObj.gallery isEqual:[NSNull null]]) {
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:adObj.gallery]];
[cell.adImageView setImageWithURLRequest:imageRequest placeholderImage:[UIImage imageNamed:#"ship_placeholder.png"] success:nil failure:nil];
}
else
{
[cell.adImageView setImage:[UIImage imageNamed:#"ship_placeholder.png"]];
}
if (_serverCallType == ServerCallTypeAdvancedSearch || _serverCallType == ServerCallTypeSearch ) {
[cell.phoneButton setHidden:NO];
[cell.categoryLabel setHidden:YES];
[cell.authorLabel setHidden:YES];
[cell.addressLabel setHidden:YES];
[cell.favButton setCenter:CGPointMake(CGRectGetMaxX(cell.phoneButton.frame) + 25.0f, CGRectGetMidY(cell.phoneButton.frame))];
} else
{
[cell.phoneButton setHidden:YES];
[cell.favButton setCenter:CGPointMake(CGRectGetWidth(cell.frame) - 30.0f, 65.0f)];
}
if (_selectionType == BBSelectionBoat || _selectionType == BBSelectionOtherBoat || _selectionType == BBlatestBoat )
{
if (adObj.price && ![adObj.price isEqualToString:#""]) {
[cell.priceLabel setHidden:NO];
[cell.priceLabel setText:adObj.price];
}
[cell.categoryLabel setCenter:CGPointMake(CGRectGetMidX(cell.authorLabel.frame), CGRectGetMinY(cell.authorLabel.frame) - 7.0f)];
if (_serverCallType == ServerCallTypeAdvancedSearch || _serverCallType == ServerCallTypeSearch)
{
[cell.authorLabel setHidden:YES];
[cell.addressLabel setHidden:YES];
}
else
{
cell.authorLabel.text = adObj.authorName;
cell.addressLabel.text = adObj.address;
[cell.authorLabel setHidden:YES];
[cell.addressLabel setHidden:NO];
}
}
else
{
[cell.priceLabel setHidden:YES];
[cell.authorLabel setHidden:YES];
[cell.addressLabel setHidden:YES];
[cell.categoryLabel setCenter:CGPointMake(CGRectGetMidX(cell.addressLabel.frame), CGRectGetMidY(cell.addressLabel.frame))];
}
[cell.favButton setSelected:adObj.isFavorite];
NSRange range = [adObj.title rangeOfString:#","];
cell.titleLabel.text = range.location == NSNotFound ? adObj.title : [adObj.title substringToIndex:range.location];
[cell.titleLabel setNumberOfLines:0];
cell.categoryLabel.text = adObj.category;
return cell;
}
Below are simple example for pass a data from one view controler to another.
//FirstViewController.m
//on button click
SecondViewController *secondViewContrler = [self.storyboard instantiateViewControllerWithIdentifier:#"SecondViewController"];
secondViewContrler.dataArray = dataArrayWithData; //assign value
//SecondViewController.h
#property (retain , nonatomic) NSMutableArray* dataArray;
//SecondViewController.m
#synthesize dataArray;

UICollectionView cell disappears on scroll

I have two collectionViews. A collectionViewController and another collectionView in the header. When I scroll down the collectionViewController, the collectionView cells of the the header collectionView disappear. There is also a segControl in the header that changes the collectionViewController cells and this also makes the header collectionView cells disappear. When the controller appears all the cells are present, BUT when i wither scroll of select the segControl the header Collection View cells disappear. The collectionViewController works fine, just the one in the header is messed up.
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if (collectionView == self.collectionView) {
return [self.dataArray count];
}
return [self.groupArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if (collectionView != self.collectionView) {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"socialCell" forIndexPath:indexPath];
PFObject *group = [self.groupArray objectAtIndex:indexPath.row];
UILabel *label = (UILabel *) [cell viewWithTag:55];
label.text = [group objectForKey:#"Title"];
return cell;
}
userPostCell *postCell = (userPostCell *) [collectionView dequeueReusableCellWithReuseIdentifier:#"postCell" forIndexPath:indexPath];
userPictureCell *pictureCell = (userPictureCell *) [collectionView dequeueReusableCellWithReuseIdentifier:#"pictureCell" forIndexPath:indexPath];
userEventCell *eventCell = (userEventCell *) [collectionView dequeueReusableCellWithReuseIdentifier:#"eventCell" forIndexPath:indexPath];
PFObject *temp = [self.dataArray objectAtIndex:indexPath.row];
if (self.dataArray == self.postsArray) {
postCell.postLabel.text = [temp objectForKey:#"stringPost"];
[self changeToCircle:postCell.profileImage];
if ([temp objectForKey:#"Event"] == nil) {
[postCell.noEventNameButton setTitle:[temp objectForKey:#"User_Name"] forState:UIControlStateNormal];
postCell.noEventNameButton.tag = indexPath.row;
postCell.nameButton.hidden = true;
postCell.noEventNameButton.hidden = false;
}
else{
[postCell.nameButton setTitle:[temp objectForKey:#"User_Name"] forState:UIControlStateNormal];
postCell.nameButton.tag = indexPath.row;
postCell.noEventNameButton.hidden = true;
postCell.nameButton.hidden = false;
//[postCell.eventButton addTarget:self action:#selector(eventPage:) forControlEvents:UIControlEventTouchUpInside];
}
[postCell.eventButton setTitle:[temp objectForKey:#"Event"] forState:UIControlStateNormal];
NSString *createdTime = [NSDateFormatter localizedStringFromDate: temp.createdAt dateStyle: NSDateFormatterNoStyle timeStyle: NSDateFormatterShortStyle];
[postCell.timeButton setTitle:createdTime forState:UIControlStateNormal];
PFFile *imageFile = [temp objectForKey:#"profileImage"];
NSData *data = [imageFile getData];
postCell.profileImage.image = [UIImage imageWithData:data];
NSArray *likeArray = [temp objectForKey:#"likes"];
NSString *likeString = [NSString stringWithFormat:#"%lu Likes", (unsigned long)likeArray.count];
if ([likeArray containsObject:[PFUser currentUser].objectId]) {
postCell.likeButton.hidden = true;
}
else{
postCell.likeButton.hidden = false;
}
NSArray *commentArray = [temp objectForKey:#"Comments"];
NSString *commentString = [NSString stringWithFormat:#"%lu Comments", (unsigned long)commentArray.count];
[postCell.likesButton setTitle:likeString forState:UIControlStateNormal];
[postCell.commentsButton setTitle:commentString forState:UIControlStateNormal];
postCell.eventButton.tag = indexPath.row;
postCell.likeButton.tag = indexPath.row;
postCell.commentsButton.tag = indexPath.row;
postCell.likesButton.tag = indexPath.row;
[postCell.likesButton addTarget:self action:#selector(likesPage:) forControlEvents:UIControlEventTouchUpInside];
[postCell.likeButton addTarget:self action:#selector(like:) forControlEvents:UIControlEventTouchUpInside];
[postCell.commentsButton addTarget:self action:#selector(commentsPage:) forControlEvents:UIControlEventTouchUpInside];
[postCell setUserInteractionEnabled:YES];
return postCell;
}
if (self.dataArray == self.personImages) {
UIImage *personImage = [self.dataArray objectAtIndex:indexPath.row];
pictureCell.userImage.image = personImage;
return pictureCell;
}
if (self.dataArray == self.eventsArray) {
[eventCell.userEvent setTitle:[temp objectForKey:#"Title"] forState:UIControlStateNormal];
eventCell.userEvent.tag = indexPath.row;
[eventCell.userEvent addTarget:self action:#selector(eventPage:) forControlEvents:UIControlEventTouchUpInside];
[eventCell.userGroup setTitle:[temp objectForKey:#"Group_Name"] forState:UIControlStateNormal];
eventCell.userGroup.tag = indexPath.row;
[eventCell.userGroup addTarget:self action:#selector(groupPage:) forControlEvents:UIControlEventTouchUpInside];
return eventCell;
}
return postCell;
}
The Seg Method:
- (IBAction)segControl:(id)sender {
UISegmentedControl *segment = (UISegmentedControl *) sender;
if (segment.selectedSegmentIndex == 0) {
self.dataArray = self.postsArray;
[self.collectionView reloadData];
}
if (segment.selectedSegmentIndex == 1) {
self.dataArray = self.personImages;
[self.collectionView reloadData];
}
if (segment.selectedSegmentIndex == 2) {
self.dataArray = self.eventsArray;
[self.collectionView reloadData];
}
}
it's late but this will help for others
i also had similar problem , i just replaced [self.myCollectionView reloadData] with [self.myCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]]; to refresh the collectionview and it shows all cells, you can try it.

UISearchBar with table view and checkbox tutorial

Can anyone suggest a tutorial which can achieve following 3 tasks for one ViewController.
1. Search names in tableView.
2. Each cell in tableView has checkBoxes.
3. Retain checked cells [state of `UIButtons`] if the user searches the name.
So far I have achieved first two tasks from this lengthly code
but unable to achieve 3rd point. Any help will be sincerely appreciated. Thanks.
There are many ways to do this. You can't expect tutorials to do exactly what you are doing.
There are many ways of doing this. One of the ways is to store the state of the checked cells in an NSArray and then load the state in cellForRowAtIndexPath data source method.
Solved my own issue with the following code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//static NSString *cellId = #"CheckBoxedCell";
NSString *cellId = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
CheckBoxedCellClass *cell = (CheckBoxedCellClass *)[self.tableViewContact dequeueReusableCellWithIdentifier:cellId];
if(!cell)
{
NSArray *nib;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass" owner:self options:nil];
}
else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass_iPad" owner:self options:nil];
}
for (id object in nib)
{
if([object isKindOfClass:[CheckBoxedCellClass class]])
{
cell = (CheckBoxedCellClass *)object;
break;
}
}
cell = [nib objectAtIndex:0];
}
//set fonts
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:10.0]];
}
else
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:14.0]];
}
//handling check box
NSInteger rowNumber = 0;
for(NSInteger i = 0; i < indexPath.section ; i++)
{
rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
SaveCheckBoxedView *saveContact;
if(isFiltered == YES)
{
saveContact = [filterdArray objectAtIndex:indexPath.row];
cell.nameLabel.text = saveContact.nameString;
cell.companyLabel.text = saveContact.companyString;
}
else
{
saveContact = [mutableArray objectAtIndex:indexPath.row];
cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.companyLabel.text = [NSString stringWithFormat:#"%#", [companyArray objectAtIndex:rowNumber]];
}
cell.invIdLabel.text = [NSString stringWithFormat:#"%#", saveContact.invitId];
UIButton *checkBox;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
}
else
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
}
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:event:) forControlEvents:UIControlEventTouchUpInside];
// handle check box view reset when scrolled
if(isFiltered == YES)
{
NSLog(#"filtered");
BOOL buttonPress = [[boolDictForSearch objectForKey:[filteredArrayOfIds objectAtIndex:indexPath.row]] boolValue];
NSLog(#"button press = %d", buttonPress);
[checkBox setSelected:buttonPress];
if(buttonPress)
{
[checkBox setImage:[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
}
else
{
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
}
checkBox.tag = indexPath.row;
}
else
{
BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:#"%d", rowNumber]] boolValue];
NSLog(#"button pressED = %d", buttonPressed);
NSLog(#"Row number = %d", rowNumber);
[checkBox setSelected:buttonPressed];
if(buttonPressed)
{
[checkBox setImage:[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
}
else
{
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
}
checkBox.tag = rowNumber;
}
[cell.contentView addSubview:checkBox];
return cell;
}
-(void)checkBoxClicked:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableViewContact];
NSIndexPath *indexPath = [self.tableViewContact indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"value of indexPath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);
UIButton *tappedButton = (UIButton*)sender;
NSLog(#"Tag number = %d", [sender tag]);
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"checkBox.png"]])
{
[sender setImage:[UIImage imageNamed: #"checkBoxMarked.png"] forState:UIControlStateNormal];
NSUserDefaults *buttonDefault = [NSUserDefaults standardUserDefaults];
[buttonDefault setBool:YES forKey:#"CHECKMARKEDKEY"];
[self.boolDict setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:#"%d", [sender tag]]];
//[self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:#"%#", saveContact.nameString]];
if(isFiltered == YES)
{
NSString *addId = [filteredArrayOfIds objectAtIndex:indexPath.row];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:addId];
NSLog(#"filterd id = %#", addId); //get filtered array here
[arrayOfIds addObject:addId];
}
else
{
NSString *finalIntId = [mutableArrayOfIds objectAtIndex:tappedButton.tag];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:finalIntId];
NSLog(#"Tagged checked button id = %#", finalIntId);
[arrayOfIds addObject:finalIntId];
}
}
else
{
[sender setImage:[UIImage imageNamed:#"checkBox.png"]forState:UIControlStateNormal];
NSLog(#"UnChecked");
[self.boolDict setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:#"%d", [sender tag]]];
//[self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:#"%#", saveContact.nameString]];
if(isFiltered == YES)
{
[arrayOfIds removeObjectIdenticalTo:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
}
else
{
[arrayOfIds removeObjectIdenticalTo:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
[self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
}
}
}

button tag issue with UISearchBar

I need to set a tag for the button created on the table view cell.
I implemented the UISearchBar and it works well.
Issue is after filtering the tableView cell, its indexpath.row changes as I am setting
'button.tag = indexPath.row'.
Is there a way to keep the row number constant for every cell?
Or is there any other solution?
Note: I have multiple sections in one UITableView and isFiltered is BOOL value which indicates user have started to type text in UISearchBar.
Implemented Searching with help of https://github.com/kwylez/IndexedTable
In cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"CheckBoxedCell";
// NSString *cellId = [NSString stringWithFormat:#"Section:%d Row:%d",indexPath.section,indexPath.row];
CheckBoxedCellClass *cell = (CheckBoxedCellClass *)[self.tableViewContact dequeueReusableCellWithIdentifier:cellId];
if(!cell)
{
NSArray *nib;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass" owner:self options:nil];
}
else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"CheckBoxedCellClass_iPad" owner:self options:nil];
}
for (id object in nib)
{
if([object isKindOfClass:[CheckBoxedCellClass class]])
{
cell = (CheckBoxedCellClass *)object;
break;
}
}
cell = [nib objectAtIndex:0];
}
SaveCheckBoxedView *saveContact;
if(isFiltered == YES)
{
saveContact = [filterdArray objectAtIndex:indexPath.row];
cell.nameLabel.text = saveContact.nameString;
}
else
{
saveContact = [mutableArray objectAtIndex:indexPath.row];
cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
}
//cell.nameLabel.text = saveContact.nameString;
cell.companyLabel.text = saveContact.companyString;
cell.invIdLabel.text = [NSString stringWithFormat:#"%d", saveContact.invitId];
//set fonts
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:10.0]];
}
else
{
[cell.companyLabel setFont:[UIFont italicSystemFontOfSize:14.0]];
}
//handling check box
NSInteger rowNumber = 0;
for(NSInteger i = 0; i < indexPath.section ; i++)
{
rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
/*if([indexPath compare:self.lastIndexPath] == NSOrderedSame)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSString *finalIntId = [mutableArrayOfIds objectAtIndex:rowNumber];
NSLog(#"Tagged checked button id = %#", finalIntId);
[arrayOfIds addObject:finalIntId];
}*/
UIButton *checkBox;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
}
else
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
}
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:event:) forControlEvents:UIControlEventTouchUpInside];
if(isFiltered == YES)
{
checkBox.tag = ;
}
else
{
checkBox.tag = rowNumber;
}
[cell.contentView addSubview:checkBox];
return cell;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
if(isFiltered == YES) {
return Nil;
} else {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
if (title == UITableViewIndexSearch) {
CGRect searchBarFrame = self.searchDisplayController.searchBar.frame;
[tableView scrollRectToVisible:searchBarFrame animated:YES];
return -1;
} else {
NSInteger count = 0;
for (NSString *character in arrayOfCharacters) {
if ([character isEqualToString:title]) {
return count;
}
count ++;
}
return 0;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(isFiltered == YES) {
return 1;
} else {
return [arrayOfCharacters count];
//return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(isFiltered == YES) {
return [filterdArray count];
} else {
//return [mutableArray count];
return [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:section]] count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if ([arrayOfCharacters count] == 0) {
return #"";
}
return [NSString stringWithFormat:#"%#", [arrayOfCharacters objectAtIndex:section]];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0)
{
isFiltered = NO;
}
else
{
isFiltered = YES;
filterdArray = [[NSMutableArray alloc] init];
for (SaveCheckBoxedView *contact in mutableArray)
{
NSRange nameRange = [contact.nameString rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound)
{
[filterdArray addObject:contact];
}
}
}
[self.tableViewContact reloadData];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filterdArray removeAllObjects];
if(searchString.length > 0)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.mySearchBar.text];
for (NSString *key in arrayOfCharacters)
{
NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate];
[filterdArray addObjectsFromArray:matches];
}
}
return YES;
}
I am describing one way to do so, you may find better way.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filterdArray removeAllObjects];
if(searchString.length > 0)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.mySearchBar.text];
for (NSString *key in arrayOfCharacters)
{
NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate];
/****see bellow****/
[filterdArray addObjectsFromArray:matches];
}
}
return YES;
}
Try to find the row number of each object of "matches". that will be the tag of your buttons. Make filterdArray an array of dictionary. Add 2 field to dictionary. one for tag another for value. in cellForRowAtIndexPath.
if(isFiltered == YES)
{
checkBox.tag = [filterdArray objectForKey: #"tag"] ;
}
else
{
checkBox.tag = rowNumber;
}

How do i untick the ticked cell when new cell ticked (exclusive uitableviewcell selection)(ios)?

I tried this:
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
// this code im trying to toggle already ticked cell
NSString *knownObject = #"YES";
NSArray *alreadyTickedBoxes;
// NSInteger dictIndex= -1;
NSMutableDictionary *dict;
for (dict in self.dataArray){
// dictIndex++;
alreadyTickedBoxes = [dict allKeysForObject:knownObject];
if (alreadyTickedBoxes.count !=0)
break;
}
if(alreadyTickedBoxes.count != 0){
[dict setObject:[NSNumber numberWithBool:NO] forKey:#"checked"];
FeedCell3 *cellToUntick = [dict objectForKey:#"cell"];
UIButton *button = (UIButton *)cellToUntick.accessoryView;
UIImage *newImage = [UIImage imageNamed:#"unticked24"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
}
// this code toggles tapped cell
NSMutableDictionary *item = [self.dataArray objectAtIndex:indexPath.row] ;
BOOL checked = [[item objectForKey:#"checked"] boolValue];
[item setObject:[NSNumber numberWithBool:!checked] forKey:#"checked"];
FeedCell3 *cell = [item objectForKey:#"cell"];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:#"unticked24"] : [UIImage imageNamed:#"ticked24"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
[tableView reloadData];
}
I got it working by just keeping a reference to the last selected index.
#pragma mark - UITableViewDelegate
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.feedTableView];
NSIndexPath *indexPath = [self.feedTableView indexPathForRowAtPoint: currentTouchPosition];
if (indexPath != nil)
{
[self tableView: self.feedTableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
// initialise previous index path to current index path
if(self.oldIndexPathRowIndex<0){
self.oldIndexPathRowIndex = indexPath.row;
}
// the following code should toggle previously selected row
if ( self.oldIndexPathRowIndex != indexPath.row) {
NSMutableDictionary *dictAtOldIndex = [self.dataArray objectAtIndex: self.oldIndexPathRowIndex];
BOOL checked = [[dictAtOldIndex objectForKey:#"checked"] boolValue];
NSString *text = [dictAtOldIndex objectForKey:#"text"] ;
NSLog(#"Toggling previously tapped row: %# checked: %d", text, checked);
[dictAtOldIndex setObject:[NSNumber numberWithBool:!checked] forKey:#"checked"];
checked = [[dictAtOldIndex objectForKey:#"checked"] boolValue];
NSLog(#"Previously tapped row: %# toggled to: %d", text, checked);
FeedCell3 *cellToUntick = [dictAtOldIndex objectForKey:#"cell"];
UIButton *button = (UIButton *)cellToUntick.accessoryView;
UIImage *newImage = [UIImage imageNamed:#"unticked40x43"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
//update current index path
self.oldIndexPathRowIndex = indexPath.row;
}
// this code toggles currently tapped row
NSMutableDictionary *item = [self.dataArray objectAtIndex:indexPath.row] ;
BOOL checked2 = [[item objectForKey:#"checked"] boolValue];
NSString *text = [item valueForKey:#"text"];
NSLog(#"Toggling currently tapped row: %# checked: %d", text, checked2);
[item setObject:[NSNumber numberWithBool:!checked2] forKey:#"checked"];
checked2 = [[item objectForKey:#"checked"] boolValue];
NSLog(#"Currently tapped row: %# toggled to: %d", text, checked2);
FeedCell3 *cell = [item objectForKey:#"cell"];
UIButton *button2 = (UIButton *)cell.accessoryView;
UIImage *newImage2 = (checked2) ? [UIImage imageNamed:#"unticked40x43"] : [UIImage imageNamed:#"ticked40x43"];
[button2 setBackgroundImage:newImage2 forState:UIControlStateNormal];
// NSLog(#"Old Index Path is now row: %d", self.oldIndexPathRowIndex);
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self tableView: self.feedTableView accessoryButtonTappedForRowWithIndexPath: indexPath];
[self.feedTableView deselectRowAtIndexPath:indexPath animated:YES];
}

Resources