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]];
}
}
}
Related
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.
I'm working with two custom UITableViewCell subclasses. They're both designed to hold the contents of a Tweet, one specific just to Tweets with text and the other for Tweets with text and an image. I'm creating both cells programatically in the subclasses and using PureLayout for auto-layout to avoid sizing issues.
Now when the tweets in the cells initially load, everything's fine and those with images in appear as they should using the right subclass and vice versa for those without images. But when I start to scroll the cells without text suddenly appear with the UIImageViews and images within them - even though there's not an actual image for the Tweet, they're loading images off the other Tweets.
I'm not sure what's going on, I believe it's an issue where i'm loading and setting up the cells in:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Although i'm also using SDWebImage to asynchronously load the images - however it works perfectly fine for the profile images with no issues on loading different images. This might be because both the TweetWithImageCell and TweetNormalCell have profile images.
Can anyone shed some light on the best method of doing this to make it work correctly?
Code is as below:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tweet = [tweetsArray objectAtIndex:indexPath.row];
if ([[tweet objectForKey:#"entities"] objectForKey:#"media"]) {
if ([[[tweet objectForKey:#"entities"] objectForKey:#"media"]isKindOfClass:[NSArray class]]) {
tweetMedia = [[tweet objectForKey:#"entities"] objectForKey:#"media"];
} else {
}
}
if ([tweetMedia objectAtIndex:0]) {
//Initial cell setup
StreamPhotoTableViewCell *cell = (StreamPhotoTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifierPhoto];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
if (cell == nil) {
cell = tweetPhotoCell;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
NSDictionary *tweetMediaFirst = [tweetMedia objectAtIndex:0];
NSString *tweetMediaUrl = [tweetMediaFirst objectForKey:#"media_url"];
[cell updateFonts];
cell.titleLabel.text = [[tweet objectForKey:#"user"] objectForKey:#"name"];
cell.userNameLabel.text = [NSString stringWithFormat:#"#%#",[[tweet objectForKey:#"user"] objectForKey:#"screen_name"]];
cell.bodyLabel.text = [tweet objectForKey:#"text"];
[cell.tweetImageView sd_setImageWithURL:[NSURL URLWithString:tweetMediaUrl]
placeholderImage:[UIImage imageNamed:#"tweetImagePlaceholder"]];
NSString *profileImageUrl = [[tweet objectForKey:#"user"] objectForKey:#"profile_image_url"];
NSString *profileImageCheck = [profileImageUrl substringFromIndex: [profileImageUrl length] - 4];
if([profileImageCheck isEqual:#".png"])
{
NSString *profileShort = [profileImageUrl substringToIndex:[profileImageUrl length] - 11];
profileImageUrlBigger = [NSString stringWithFormat:#"%#.png", profileShort];
}
else if([profileImageCheck isEqualToString:#"jpeg"])
{
NSString *profileShort = [profileImageUrl substringToIndex:[profileImageUrl length] - 12];
profileImageUrlBigger = [NSString stringWithFormat:#"%#.jpeg", profileShort];
}
else if([profileImageCheck isEqualToString:#".jpg"])
{
NSString *profileShort = [profileImageUrl substringToIndex:[profileImageUrl length] - 11];
profileImageUrlBigger = [NSString stringWithFormat:#"%#.jpg", profileShort];
}
[cell.profileImageView sd_setImageWithURL:[NSURL URLWithString:profileImageUrlBigger]
placeholderImage:[UIImage imageNamed:#"tweetImagePlaceholder"]];
//Reply button setup/action
[cell.replyButton addTarget:self action:#selector(replyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.replyButton setAccessibilityHint:[[tweet objectForKey:#"user"] objectForKey:#"screen_name"]];
//Retweet button setup/action
if([[tweet objectForKey:#"retweeted"] isEqual:#0]) {
[cell.retweetButton addTarget:self action:#selector(retweetButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.retweetButton setImage:[UIImage imageNamed:#"retweetIcon"] forState:UIControlStateNormal];
[cell.retweetButton setAccessibilityHint:[tweet objectForKey:#"id_str"]];
}
else {
[cell.retweetButton addTarget:self action:#selector(retweetedButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.retweetButton setImage:[UIImage imageNamed:#"retweetedIcon"] forState:UIControlStateNormal];
[cell.retweetButton setAccessibilityHint:[tweet objectForKey:#"id_str"]];
}
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
return cell;
}
else {
//Initial cell setup
StreamTableViewCell *cell = (StreamTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
if (cell == nil) {
cell = tweetCell;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
[cell updateFonts];
cell.titleLabel.text = [[tweet objectForKey:#"user"] objectForKey:#"name"];
cell.userNameLabel.text = [NSString stringWithFormat:#"#%#",[[tweet objectForKey:#"user"] objectForKey:#"screen_name"]];
cell.bodyLabel.text = [tweet objectForKey:#"text"];
NSString *profileImageUrl = [[tweet objectForKey:#"user"] objectForKey:#"profile_image_url"];
NSString *profileImageCheck = [profileImageUrl substringFromIndex: [profileImageUrl length] - 4];
if([profileImageCheck isEqual:#".png"])
{
NSString *profileShort = [profileImageUrl substringToIndex:[profileImageUrl length] - 11];
profileImageUrlBigger = [NSString stringWithFormat:#"%#.png", profileShort];
}
else if([profileImageCheck isEqualToString:#"jpeg"])
{
NSString *profileShort = [profileImageUrl substringToIndex:[profileImageUrl length] - 12];
profileImageUrlBigger = [NSString stringWithFormat:#"%#.jpeg", profileShort];
}
else if([profileImageCheck isEqualToString:#".jpg"])
{
NSString *profileShort = [profileImageUrl substringToIndex:[profileImageUrl length] - 11];
profileImageUrlBigger = [NSString stringWithFormat:#"%#.jpg", profileShort];
}
[cell.profileImageView sd_setImageWithURL:[NSURL URLWithString:profileImageUrlBigger]
placeholderImage:[UIImage imageNamed:#"tweetImagePlaceholder"]];
//Reply button setup/action
[cell.replyButton addTarget:self action:#selector(replyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.replyButton setAccessibilityHint:[[tweet objectForKey:#"user"] objectForKey:#"screen_name"]];
//Retweet button setup/action
[cell.retweetButton setAccessibilityHint:[tweet objectForKey:#"id_str"]];
if([[tweet objectForKey:#"retweeted"] isEqual:#0]) {
[cell.retweetButton addTarget:self action:#selector(retweetButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.retweetButton setImage:[UIImage imageNamed:#"retweetIcon"] forState:UIControlStateNormal];
}
else {
[cell.retweetButton addTarget:self action:#selector(retweetedButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.retweetButton setImage:[UIImage imageNamed:#"retweetedIcon"] forState:UIControlStateNormal];
}
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
return cell;
}
return nil;
}
This condition will be true if your array have elements in it. So the else part won't execute in that case.
if ([tweetMedia objectAtIndex:0])
Oddly enough this seemed to solve the problem:
if ([[[[tweetsArray objectAtIndex:indexPath.row] objectForKey:#"entities"] objectForKey:#"media"] objectAtIndex:0])
Rather than already assigning the contents of the NSDictionary *tweet and NSMutableArray *tweetMedia and deliberately accessing the main tweetsArray through indexPath of each cell.
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]];
}
}
}
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];
}
I have an existing UITableView that lists a number of cafes in the area. The data for each cafe is being pulled from a MySQL database. When a user clicks on a cafe (cell), it brings a user to a detail view. Currently, users can "Favorite" a cafe by clicking on the star image in each cell (this adds the favorited cell to FavoritesTableView). However, I want users to be able to add a cafe to the FavoritesTableView from the DetailView as well (in other words, "favorite" a cafe from the DetailView). Does anyone know how I would implement this?
Right now, I have the star button in place in my DetailView.m (cafe details):
- (IBAction)buttonpressed:(UIButton *)fave {
if (!checked) {
[checkedButton setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
checked = YES;
}
else if (checked) {
[checkedButton setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
checked = NO;
}
}
ViewController.m (cafes tableview)
- (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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
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"];
}
NSMutableDictionary *item = [Strains objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"StrainTableCell"];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
NSLog(#"%i",checked);
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSLog(#"made it here and event is %#",event);
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.StrainTableView];
NSIndexPath * indexPath ;
indexPath = [self.StrainTableView indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"indexpath is below");
NSLog(#"%#",indexPath);
if (indexPath != Nil)
{
NSMutableDictionary *item = [Strains objectAtIndex:indexPath.row];
BOOL isItChecked = [[item objectForKey:#"checked"] boolValue];
NSMutableArray *quickArray = [[NSMutableArray alloc] initWithArray:Strains];
[quickArray replaceObjectAtIndex:indexPath.row withObject:item];
[item setObject:[NSNumber numberWithBool:!isItChecked] forKey:#"checked"];
Strains = [quickArray copy];
[StrainTableView reloadData];
}
}
- (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)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"strains"] != Nil) {
NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:#"strains"];
Strains = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
}
if (favoritesArray == Nil) {
favoritesArray = [[NSMutableSet alloc] init];
}
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"] != Nil) {
NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"];
favoritesArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
}
I'm just not sure what sort of code I would add to this in order to make the "Checked" button add the selected cell from UITableView to FavoritesTableView.
Hope this made sense. Any ideas?
From a maintainability stand point, the approach I generally take might not be the best. However, from an implementation stand point, it's very easy. I pass a reference to my object (in your case, the object for the table view that was selected) to the details view. From the details view, I can update that object by switching the flag. Since this object is the same object as the table view, updating it will also update the table view (you may have to redraw the table view cell). Last, I update the database from the details view.
Edit
So in your code, it would look like this.
- (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"];
//YOU'RE ALREADY DOING IT :)
detailViewController.strainDetail = [searchResults objectAtIndex:indexPath.row];
} else {
detailViewController.title = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
//YOU'RE ALREADY DOING IT :)
detailViewController.strainDetail = [Strains objectAtIndex:indexPath.row];
NSLog(#"%#", Strains);
}
[self.navigationController pushViewController:detailViewController animated:YES];
}
You're already sending a reference to the details view! This makes things easy. In your details view, whenever someone favorites a strain, set the favorite flag for the strainDetail object. This will also update the strainDetail object in the table view. It works like this because you're passing a reference (also referred to as a pointer) to the detail view. In other words, both of your strainDetail objects, aren't objects but pointers to a memory address. If you update either strainDetail, the the memory address for both strainDetail gets changed. Not the strainDetail pointer itself. Here's an link for further explanation https://softwareengineering.stackexchange.com/questions/17898/whats-a-nice-explanation-for-pointers
So your Details view handler will look something like this
- (IBAction)buttonpressed:(UIButton *)fave {
if (!checked) {
[checkedButton setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
checked = YES;
}
else if (checked) {
[checkedButton setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
checked = NO;
}
//updates in both the detail view and the table view
BOOL isItChecked = [[self.strainDetail objectForKey:#"checked"] boolValue];
[self.strainDetail setObject:[NSNumber numberWithBool:checked] forKey:#"checked"];
}
I also suggest creating a Strain class to hold all of your strain data. Working with dictionaries is not fun, is error prone, and takes forever to figure out what keys you need.
You can save "favorite" state in a global variable/singleton and retrieve it when needed.
This way, even if your table view is deallocated, you won't lose its cells' state.