How to Hide UIButton in tableView after getting certain JSON response - ios

Here in this tableView cell i have created a button i want to hide that button after getting response "1". I am doing it in following way but not working still the cell is showing the button.How would i do that.
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
MyVideos *myvidoeclips = [park objectAtIndex:indexPath.row];
UILabel *lbl2=(UILabel*)[cell viewWithTag:777];
NSString *stateus = [myvidoeclips valueForKey:#"state"];
if([stateus isEqual: #"0"]){
[lbl2 setText:#"Under Moderation"];
}
if([stateus isEqual: #"1"]){
[lbl2 setText:#"Published"];
}
if([stateus isEqual: #"4"]){
[lbl2 setText:#"Rejected"];
}
lbl2.textColor=[UIColor whiteColor];
// Here is my button which i want to hide
UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(216, 130, 64, 30)];
NSString *strFlagValue = [[NSString alloc]init];
strFlagValue = [myvidoeclips valueForKey:#"state"];
if ([strFlagValue isEqualToString:#"1"])
{
flag = true;
}
else
{
flag = false;
}
if (flag)
{
button.hidden = true;
}
else
{
button.hidden = false;
}
[button addTarget:self action:#selector(yourEditButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; button.tag = indexPath.row;
[button setImage:[UIImage imageNamed:#"btn-details.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:button];
NSLog(#"sender.tag cell is%ld ",(long)button.tag);
}

In cellForRowAtIndex check flag.
Flag will be true or false depending upon your JSON response ( Array / Dictionary )
BOOL flag;
NSString *strFlagValue = [[NSString alloc]init];
strFlagValue = [[array objectAtIndex:indexPath.row] valueForKey:#"Key_From_You_Get_1_Or_0"];
if ([strFlagValue isEqualToString:#"1"])
{
flag = true;
}
else
{
flag = false;
}
if (flag)
{
cell.button.hidden = true;
}
else
{
cell.button.hidden = false;
}
Also check your cell in cellForRowAtIndex must be reusable with identifier.
If you are sure to get "1" or "0" every time from JSON(Array). then below sort code is enough.
BOOL flag = [[[array objectAtIndex:indexPath.row] valueForKey:#"Key_From_You_Get_1_Or_0"] boolValue];
cell.button.hidden = flag;
Whole cellForRowAtIndexPath ( Logic you are writing in your question at wrong method )
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ID_CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = (CustomCell *)[[[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil] objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
BOOL flag = [[[array objectAtIndex:indexPath.row] valueForKey:#"Key_From_You_Get_1_Or_0"] boolValue];
cell.btn1.hidden = flag;
NSString *strFlagValue = [[NSString alloc]init];
strFlagValue = [[array objectAtIndex:indexPath.row] valueForKey:#"Key_From_You_Get_1_Or_0"];
if ([strFlagValue isEqualToString:#"1"])
{
flag = true;
}
else
{
flag = false;
}
if (flag)
{
cell.btn1.hidden = 1;
}
else
{
cell.btn1.hidden = 0;
}
return cell;
}

For static table cells, create an IBOutlet of UIButton and hide while checking condition using json data.
For dynamic table cells, need to identify the row number for which button needs to be hidden.
Example :- There is an array contains multiple dictionary.
NSDictionary* dict = [array objectAtIndex:indexPath.row];
BOOL isButtonHidden = [dict objectForKey:#"KeyName"];
cell.button.hidden = isButtonHidden
Hope this solution help you..Thanks

Related

Adding/removing object to mutable array

I have allSpecialities array, and selectedSpecialities array. I'm downloading those arrays from the server, parse them to object and adding them to those arrays. Now, I want to check/uncheck some specialities. I've tried with containsObject, but that's not working, because those objects are not on the same memory location. This is code that I've done so far, and it's working, but I have problem how to add them to this array.
in cellForRowAtIndexPath:
for (Speciality *specTemp in self.selectedSpecialities) {
if (speciality.specialityId == specTemp.specialityId) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
break;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
in didSelect:
Speciality *speciality = [[Speciality alloc]init];
speciality = self.allSpecialities[indexPath.row];
NSMutableArray *tempSelectedSpecialities = [[NSMutableArray alloc]initWithArray:self.selectedSpecialities];
int i=0;
for (Speciality *tempSpeciality in tempSelectedSpecialities) {
if (tempSpeciality.specialityId == speciality.specialityId) {
[self.selectedSpecialities removeObjectAtIndex:i];
}
else {
}
i++;
}
[self.delegate companySpecialities:self.selectedSpecialities];
[self.specialitiesTableView reloadData];
I have declare one Mutable array in .h to store a data
NSMutableArray *selectedMarks;
assign memory in viewDidLoad
selectedMarks = [NSMutableArray new];
add and remove object in didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = (TableViewCell *)[self.tblview cellForRowAtIndexPath:indexPath];
NSString *strIndex=[NSString stringWithFormat:#"%ld",(long)indexPath.section];
if ([selectedMarks containsObject:strIndex])// Is selected?
{
[selectedMarks removeObject:strIndex];
}
else{
[selectedMarks addObject:strIndex];
}
}
in cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CRTableViewCellIdentifier = #"TableViewCell";
TableViewCell *cell = (TableViewCell *)[self.tblview dequeueReusableCellWithIdentifier:CRTableViewCellIdentifier];
if (cell == nil) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CRTableViewCellIdentifier];
}
cell.backgroundColor=[UIColor colorWithRed:122/255.0 green:196/255.0 blue:251/255.0 alpha:1];
// Check if the cell is currently selected (marked)
NSString *txtQRCodeid = [[[dictListQR objectForKey:#"boxlist"]objectAtIndex:indexPath.section]valueForKey:#"qr_code_id"];
NSString *text1 = [[[dictListQR objectForKey:#"boxlist"]objectAtIndex:indexPath.section]valueForKey:#"box_name"];
NSString *text=[NSString stringWithFormat:#"QR Code %ld with %#",indexPath.section+1,text1];
cell.isSelected = [selectedQR containsObject:txtQRCodeid] ? YES : NO;
if (cell.isSelected) {
[cell.btnSelection setImage:[UIImage imageNamed:#"check"] ];
// set image of selected
}
else{
[cell.btnSelection setImage:[UIImage imageNamed:#"uncheck"] ];
// set unselected image
}
cell.lblQRcodeText.text=text;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15];
return cell;
}
It's Work for me

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.

UITableView calling the another UITableView cellForRowAtIndexPath

I have two UIViewControllers with tableview. When the first cell loads in the second UIViewController it calls the cellForRowAtIndexPath in the same class but when it loads the second cell it calls the first viewControllers cellForRowAtIndexPath.
My code as follows:
SecondViewController:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NotificationsTableViewCell *cell = [self.notificationsTableView dequeueReusableCellWithIdentifier:#"NotificationCell"];
if(cell == nil)
{
cell = [[NotificationsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"NotificationCell"];
}
NSMutableDictionary *cellData = [self.databaseCall transactionFromDatabase:indexPath.row];
NSLog(#"%#", cellData);
cell.goalNameLabel.text = [cellData objectForKey:#"categoryName"];
NSString *cardTypeId = [cellData objectForKey:#"cardTypeId"];
NSString *tipsId = [cellData objectForKey:#"tipsId"];
if([self.defaultCardTypeId containsObject:cardTypeId])
{
NSUInteger index = [self.defaultCardTypeId indexOfObject:cardTypeId];
[self.defaultCardTypeId replaceObjectAtIndex:index withObject:cardTypeId];
}
else{
[self.defaultCardTypeId addObject:cardTypeId];
}
if([self.defaultTipId containsObject:tipsId])
{
NSUInteger index = [self.defaultCardTypeId indexOfObject:cardTypeId];
[self.defaultTipId replaceObjectAtIndex:index withObject:cardTypeId];
}
else{
[self.defaultTipId addObject:tipsId];
}
if([cardTypeId isEqualToString:#"1"])
{
UIImage *cellImage = [UIImage imageNamed:#"icon2.jpg"];
cell.cardTypeImage.image = cellImage;
cell.cardTypeLabel.text = #"GOOD TO KNOW";
cell.cardTypeLabel.textColor = [UIColor colorWithRed:252/255.0 green:171/255.0 blue:19/255.0 alpha:1];
}
if([cardTypeId isEqualToString:#"2"])
{
UIImage *cellImage = [UIImage imageNamed:#"icon1.jpg"];
cell.cardTypeImage.image = cellImage;
cell.cardTypeLabel.text = #"TO CONSIDER";
cell.cardTypeLabel.textColor = [UIColor colorWithRed:0/255.0 green:191/255.0 blue:243/255.0 alpha:1];
}
cell.notificationCard.layer.cornerRadius = 5;
// Configure the cell...
return cell;
}
FirstViewController:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
GoalsCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"GoalsListCell" forIndexPath:indexPath];
if(cell == nil)
{
cell = [[GoalsCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"GoalsListCell"];
}
NSInteger indexOfCategory = [self.databaseCall.arrColumnName indexOfObject:#"CategoryName"];
NSInteger indexOfImage = [self.databaseCall.arrColumnName indexOfObject:#"CategoryImage"];
NSInteger indexOfActive = [self.databaseCall.arrColumnName indexOfObject:#"coulmn"];
//Assigning the contents of cell
cell.goalName.text = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfCategory]];
NSString *categoryImage = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfImage]];
NSString *activeStatus = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfActive]];
UIImage *cellImage = [UIImage imageNamed:categoryImage];
cell.goalImage.image = cellImage;
[cell.favouriteButton addTarget:self action:#selector(favouriteButtonPressed:) forControlEvents:UIControlEventTouchDown];
NSMutableString *selectedRowImage = [[NSMutableString alloc] initWithString:#""];
//Checking whether the category is selected by user or not
if([activeStatus isEqualToString:#"yes"])
{
selectedRowImage = [NSMutableString stringWithFormat:#"starsel.png"];
}
else
{
selectedRowImage = [NSMutableString stringWithFormat:#"stardef.png"];
}
UIImage *favouriteIconImage = [UIImage imageNamed:selectedRowImage];
[cell.favouriteButton setBackgroundImage:favouriteIconImage forState:UIControlStateNormal];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
return cell;
}
Thanks in advance.
First of all i would say sorry for this stupid question.
The problem is due to the tableview datasource as specifies by #Paulw11, #Onik IV, #Kannan Vora. The secondViewController tableView has the datasource of firstViewController.

iOS UITableView shows content of an old custom cell after reload but selecting it pushes to correct data

I have a very weird behavior with a UITableViewController in my project.
Normally it works perfectly but in one specific case it doesn't.
I have a dynamic table view with one custom type of cell. After filling all the data into the data source the table shows all the content correctly. There is a Pull-to-Refresh that updates the data source and table correctly. There are some filter buttons that update the only section with an animation correctly.
But if I click on one the detail view pushes into and if I go back click on one of these filter buttons again all the table view cells update except the ones I clicked. But if I click on this one again the detail view appears with the data of the cell that used to be there.
So the data updates just fine but the visible doesn't.
I would appreciate any suggestions. Thank you
P.S: Yes I do call the deselectRowAtIndexPath: method in the didSelectRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = #"BANF";
BANFCell *cell = (BANFCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
if (cell == nil) {
cell = [[BANFCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// collect required data
Requisition *req;
// for right section
if ([self.tableView numberOfSections] == 1) {
req = [recent objectAtIndex:indexPath.row];
} else {
if (indexPath.section == 1) {
req = [recent objectAtIndex:indexPath.row];
} else {
req = [notSent objectAtIndex:indexPath.row];
}
}
NSMutableArray *shortTexts = [[NSMutableArray alloc] init];
// get description text and sort short texts ascending
// also the amount and currency
NSString *reqDescript;
NSString *amount;
NSString *currency;
for (Trait *trait in req.traits) {
if ([trait.name isEqualToString:#"DESCRIPTION"] && trait.value.length > 0) {
reqDescript = trait.value;
}
if ([trait.name isEqualToString:#"TOTAL_AMOUNT"] && trait.value.length > 0) {
amount = trait.value;
}
if ([trait.name isEqualToString:#"CURRENCY"] && trait.value.length > 0) {
currency = trait.value;
}
}
NSString *amountAndCurreny;
if (amount) {
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setCurrencyCode:currency];
amountAndCurreny = [currencyFormatter stringFromNumber:[NSNumber numberWithDouble:amount.doubleValue]];
} else
amountAndCurreny = #"";
cell.amountLabel.text = amountAndCurreny;
NSArray *descriptors = [NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:#"itm_number"
ascending:YES], nil];
NSArray *orderedArray = [req.positions sortedArrayUsingDescriptors:descriptors];
for (Position *position in orderedArray) {
for (Trait *trait in position.traits) {
if ([trait.name isEqualToString:#"SHORT_TEXT"] && trait.value.length > 0) {
[shortTexts addObject:trait.value];
}
}
}
UIImage *bgImage = [UIImage imageNamed:#"tableBG"];
cell.backgroundView = [[UIImageView alloc] initWithImage:bgImage];
// filling them in
if (req.iD.integerValue < 0) {
[cell.histLabel setText:NSLocalizedString(#"New", nil)];
} else {
[cell.histLabel setText:req.iD.stringValue];
}
[cell.datelabel setText:[labelDateFormatter stringFromDate:req.createDate]];
switch (req.status) {
case ReqStatusNew: [cell.imageView setImage:nil];
break;
case ReqStatusSaved: [cell.imageView setImage:[UIImage imageNamed:#"istGespeichertKiste.png"]];
break;
case ReqStatusApproved: [cell.imageView setImage:[UIImage imageNamed:#"genehmigtKiste.png"]];
break;
case ReqStatusInWFF: [cell.imageView setImage:[UIImage imageNamed:#"workflowKiste.png"]];
break;
case ReqStatusNotApproved: [cell.imageView setImage:[UIImage imageNamed:#"abgelehntKiste.png"]];
break;
case ReqStatusOrdered: [cell.imageView setImage:[UIImage imageNamed:#"istBestelltKiste.png"]];
break;
case ReqStatusDelivered: [cell.imageView setImage:[UIImage imageNamed:#"geliefertKiste.png"]];
break;
}
cell.shortTextLabel.marqueeType = MLContinuous;
cell.shortTextLabel.rate = 50;
cell.shortTextLabel.textAlignment = NSTextAlignmentLeft;
if (reqDescript == nil) {
cell.shortTextLabel.text = [shortTexts componentsJoinedByString:#", "];
} else if (shortTexts.count > 0) {
cell.shortTextLabel.text = [NSString stringWithFormat:#"%#: %#", reqDescript, [shortTexts componentsJoinedByString:#", "]];
} else {
cell.shortTextLabel.text = reqDescript;
}
[cell.shortTextLabel setFrame:CGRectMake(56, 35, 168, 18)];
return cell;
}
In viewWillAppear: I just set the buttons in the navigationcontroller and call
[tableview reloadData]
In viewDidLoad: just adding the delegate of the refresh control
The refresh control just calls [tableview reloadData] after updating the recent and notSent arrays from Core Data
A filter button just calls:
- (IBAction)filterPressed:(UIButton *)sender {
sender.selected = !sender.selected;
NSArray *filters = [dvFilterList componentsSeparatedByString:#","];
if ([[NSUserDefaults standardUserDefaults] boolForKey:[filters objectAtIndex:sender.tag]]){
[[NSUserDefaults standardUserDefaults] setBool:NO
forKey:[filters objectAtIndex:sender.tag]];
} else {
[[NSUserDefaults standardUserDefaults] setBool:YES
forKey:[filters objectAtIndex:sender.tag]];
}
[self updateTableViewData];
// only the section with the recent banfs
NSInteger section = [self numberOfSectionsInTableView:self.tableView] - 1;
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section]
withRowAnimation:UITableViewRowAnimationFade];
}
(updateTableViewData is the method that just updates the recent and notSent arrays from Core Data)
You can try this ,
[tableView reloadData];
You can write this in cellForRowAtIndexPath
BANFCell *cell = (BANFCell *)[tableView dequeueReusableCellWithIdentifier:nil
forIndexPath:indexPath];
I finally found the solution by myself.
In my didSelectRowAtIndexPath: method I call performSegueWithIdentifier: and by giving the selected row as sender variable Xcode is somehow saving just the look of the cell in background that can only be deleted by removing the whole view controller from the stack.
Now I just give self as the sender because I don't need the variable.
So I code this:
[self performSegueWithIdentifier:#"goToReq" sender:self];
Instead of this:
[self performSegueWithIdentifier:#"goToReq" sender:[self tableView:tableView
cellForRowAtIndexPath:indexPath]];
I know this is not the answer for the original question, but might help someone else seeing similar problems.
I've encountered similar behavior with buggy code like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (condition)
{
CustomCell1* cell = [tableView dequeueReusableCellWithIdentifier:#"custom1" forIndexPath:indexPath];
// configure cell
// !! note how "return cell;" is missing !!
}
CustomCell2* cell = [tableView dequeueReusableCellWithIdentifier:#"custom2" forIndexPath:indexPath];
// configure cell
return cell;
}
Was fixed by actually returning the special-case cell from the conditional branch.

Custom TableViewCell not updating

I want to set the checkmark in front of the cell. When I click on the checkmark icon the correct function is called and the datasource is changed.
I call [table reloadData] and after that even cellForRowAtIndexPath is also called but it is always dequeing the old table cell and not reloading it with the new data source..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"CheckboxCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSLog(#"cellForRowAtIndexPath row: %d", indexPath.row);
// use CustomCell layout
CheckboxCell *checkboxCell;
if(cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CheckboxCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
checkboxCell = (CheckboxCell *)currentObject;
break;
}
}
} else {
checkboxCell = (CheckboxCell *)cell; // return cell;
}
Observation *observation = [observations objectAtIndex:indexPath.row];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd.MM.yyyy";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *nowString = [dateFormatter stringFromDate:observation.date];
[dateFormatter release];
NSString *amountString = [[NSString alloc] initWithFormat:#"%d", observation.amount];
checkboxCell.name.text = [observation.organism getNameDe];
checkboxCell.date.text = nowString;
checkboxCell.amount.text = amountString;
checkboxCell.latName.text = [observation.organism getLatName];
// Define the action on the button and the current row index as tag
[checkboxCell.checkbox addTarget:self action:#selector(checkboxEvent:) forControlEvents:UIControlEventTouchUpInside];
[checkboxCell.checkbox setTag:observation.observationId];
// Define the action on the button and the current row index as tag
[checkboxCell.remove addTarget:self action:#selector(removeEvent:) forControlEvents:UIControlEventTouchUpInside];
[checkboxCell.remove setTag:observation.observationId];
// Set checkbox icon
if(observation.submitToServer) {
NSLog(#"CHECKED");
checkboxCell.checkbox.imageView.image = [UIImage imageNamed:#"check_icon.png"];
} else {
NSLog(#"UNCHECKED");
checkboxCell.checkbox.imageView.image = [UIImage imageNamed:#"checkbox.gif"];
}
[amountString release];
[observation release];
return checkboxCell;
// Set checkbox icon
if(observation.submitToServer) {
NSLog(#"CHECKED");
checkboxCell.checkbox.imageView.image = [UIImage imageNamed:#"check_icon.png"];
} else {
NSLog(#"UNCHECKED");
checkboxCell.checkbox.imageView.image = [UIImage imageNamed:#"checkbox.gif"];
}
[amountString release];
[observation release];
return checkboxCell;
}
I think I'm doing something in the cellForRowAtIndexPath wrong.. Can anybody help me?
Edit:
The first problem could be fixed (Thanks to Maggie). Now the checkmark is changing the first time correctly. But somehow if I change it on another cell its crashing on the following line:
- (void) checkboxEvent:(UIButton *)sender
{
UIButton *button = (UIButton *)sender;
NSNumber *number = [NSNumber numberWithInt:button.tag];
for(Observation *ob in observations) {
if(ob.observationId == [number intValue]) { // <---- IT'S CRASHING HERE
ob.submitToServer = !ob.submitToServer;
NSLog(#"New value: %#", (ob.submitToServer) ? #"YES" : #"NO");
}
}
[table reloadData];
}
But the observation object isn't nil. Any ideas?
Replace
else {
return cell;
}
part with
else {
checkboxCell = (CheckboxCell *)cell;
}
and fill your checkboxCell with apropriate data.

Resources