I am trying to create an expandable table view, however when I click on one of the cells I load a .xib file to format the subviews, however when I click the cell again the .xib format remains and messes with the view of the cells. Is there a better way to make the expandable table view?
Code:
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 28;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self tableView:tableView canCollapseSection:section])
{
if ([expandedSections containsIndex:section])
{
return [ticketList count];
}
return 1; // only top row showing
}
// Return the number of rows in the section.
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 72;
}
Load the xib here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"reuse"];
}
// Configure the cell...
NSLog(#"Number: %d", indexPath.section);
NSArray *items = [[NSArray alloc] initWithObjects:#"Cleanliness", #"Door", #"Peek Hole", #"Sink", #"Towel Rack", #"Closet", #"Carpet", #"Wall", #"Bed", #"Matress", #"Mattress Cover", #"Fridge", #"Blinds", #"Window", #"Screen", #"Air Conditioning", #"Chair", #"Desk", #"Garbage bin", #"Shelves", #"Phone", #"Jacks", #"Lights", #"Smoke Detector", #"Heat Detector", #"Light bulb", #"Deep Cleaning", #"Final Prep", nil];
if (!indexPath.row)
{
// first row
cell.textLabel.text = items[indexPath.section]; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
}
else
{
}
}
else
{
[self.tableView registerNib:[UINib nibWithNibName:#"HelpDeskCell" bundle:nil] forCellReuseIdentifier:#"Cell"];
static NSString *CellIdentifier = #"Cell";
HelpDeskCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[HelpDeskCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
CGFloat fontsize = 16;
if([[[ticketList objectAtIndex:indexPath.row] objectForKey:#"priority"] isEqualToString:#"Critical"]){
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:1 green:0.5 blue:0.5 alpha:1.0]];
}
else{
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:0.925 green:0.925 blue:0.925 alpha:1.0]];
}
[cell.IDLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
//reduce fontsize to 12 for the information labels
//same on all devices and orientations
fontsize = 12;
//ticket status label
[cell.statusLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.statusLabel setTextColor:[UIColor whiteColor]];
//ticket category label
[cell.categoryLabel setBackgroundColor:[UIColor grayColor]];
[cell.categoryLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.categoryLabel setTextColor:[UIColor whiteColor]];
//ticket title label
[cell.titleLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.titleLabel setTextColor:[UIColor blackColor]];
//Label holds the user that submitted the ticket
[cell.submittedLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.submittedLabel setTextColor:[UIColor blackColor]];
//Label holds the user currently working on the ticket
[cell.handleLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.handleLabel setTextColor:[UIColor blackColor]];
//ticket date label
[cell.dateLabel setFont:[UIFont systemFontOfSize:fontsize]];
// Set the text of the subviews
NSString * ticketIdStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"ticket_id"];
[cell.IDLabel setText:ticketIdStr];
NSString * ticketStatusStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"status"];
[cell.statusLabel setText:ticketStatusStr];
if([ticketStatusStr isEqualToString:#"Open"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0 green:0.6 blue:0.8 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"In Progress"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:1.0 green:0.733 blue:0.2 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Resolved"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.6 green:0.8 blue:0 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Closed"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1.0]];
}
NSString * categoryStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"category"];
[cell.categoryLabel setText:categoryStr];
NSString * titleStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"title"];
NSString * userIDStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"user_id"];
NSString * handledByStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"handled_by"];
[cell.titleLabel setText: [NSString stringWithFormat:#"Title: %#", titleStr]];
[cell.submittedLabel setText: [NSString stringWithFormat:#"Submitted By: %#", userIDStr]];
[cell.handleLabel setText: [NSString stringWithFormat:#"Handled By: %#", handledByStr]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *orignalDate = [dateFormatter dateFromString:[[[ticketList objectAtIndex:indexPath.row] objectForKey:#"date_submitted"] substringToIndex:10]];
[dateFormatter setDateFormat:#"MMMM dd, yyyy"];
NSString * ticketDateStr = [dateFormatter stringFromDate:orignalDate];
[cell.dateLabel setText:ticketDateStr];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
return cell;
}
Expand and Collapse here:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
[self.tableView reloadData];
}
}
Update
The main cell is a list of items and the expanding cell is suppose to be tickets from a sql database. I use a xib file to format the tickets
but when I collapse the cell which contains the items, this image remains and covers up the item cells
For creating expandable table view on clicking of UITableViewCell simply add a new cell in existing UITableView
[self.tableview insertRowsAtIndexPath:indexPath
withRowAnimation:UITableViewRowAnimationAutomatic];
Related
UPDATE
Alright, so I pull information from a mysql database and then display it in a table, where each cell contains information for a specific ticket corresponding to information in the mysql database.
However, in another function I update the the information for a certain ticket (in the database) and want to update the cells holding the information of the ticket accordingly.
The main issue is that I'm unable to call each cell on its own so I can just update the information in the cell without having to update (reloading) all cells.
So say I update the information for ticket #2. I want a way I can call cell #2 and update the information just for that cell.
So, I'm currently creating my cells like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
int count = 0;
static NSString *CellIdentifier1 = #"Cell1";
cell *cell1 = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if(cell1 == nil){
cell1 = [[cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];
}
static NSString *CellIdentifier = #"Cell";
HelpDeskCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
items = [[NSArray alloc] initWithObjects:#"Cleanliness", #"Door", #"Peek Hole", #"Sink", #"Towel Rack", #"Closet", #"Carpet", #"Wall", #"Bed", #"Matress", #"Mattress Cover", #"Fridge", #"Blinds", #"Window", #"Screen", #"Air Conditioning", #"Chair", #"Desk", #"Garbage bin", #"Shelves", #"Phone", #"Jacks", #"Lights", #"Smoke Detector", #"Heat Detector", #"Light bulb", #"Deep Cleaning", #"Final Prep", nil];
if (!indexPath.row)
{
count = 1;
// first row
NSString *title;
if (self.filterClass.orderedBy == 1) {
title = [NSString stringWithFormat:#"Room: %d (%d)", indexPath.section + 1 ,myArray[indexPath.section]];
}
else {
title = [NSString stringWithFormat:#"%# (%d)", items[indexPath.section],myArray[indexPath.section]];
}
[cell1.titleLabel setFont:[UIFont systemFontOfSize:18]];
[cell1.titleLabel setText:title];
if (myArray[indexPath.section] > 0) {
[cell1.canOpen setFont:[UIFont systemFontOfSize:18]];
[cell1.canOpen setText:#">"];
}
else {
[cell1.canOpen setFont:[UIFont systemFontOfSize:18]];
[cell1.canOpen setText:#""];
}
if ([expandedSections containsIndex:indexPath.section])
{
}
else
{
}
}
else
{
int row = indexPath.row - 1;
int section = indexPath.section;
if(cell == nil){
cell = [[HelpDeskCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
CGFloat fontsize = 16;
if([[[[multiArray objectAtIndex:section] objectAtIndex:row]
objectForKey:#"priority"] isEqualToString:#"Critical"]){
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:1 green:0.5 blue:0.5 alpha:1.0]];
}
else{
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:0.925 green:0.925 blue:0.925 alpha:1.0]];
}
[cell.IDLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
//reduce fontsize to 12 for the information labels
//same on all devices and orientations
fontsize = 12;
//ticket status label
[cell.statusLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.statusLabel setTextColor:[UIColor whiteColor]];
//ticket category label
[cell.categoryLabel setBackgroundColor:[UIColor grayColor]];
[cell.categoryLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.categoryLabel setTextColor:[UIColor whiteColor]];
//ticket title label
[cell.titleLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.titleLabel setTextColor:[UIColor blackColor]];
//Label holds the user that submitted the ticket
[cell.submittedLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.submittedLabel setTextColor:[UIColor blackColor]];
//Label holds the user currently working on the ticket
[cell.handleLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.handleLabel setTextColor:[UIColor blackColor]];
//ticket date label
[cell.dateLabel setFont:[UIFont systemFontOfSize:fontsize]];
// Set the text of the subviews
NSString * ticketIdStr = [[[multiArray objectAtIndex:section] objectAtIndex:row] objectForKey:#"ticket_id"];
[cell.IDLabel setText:ticketIdStr];
NSString * ticketStatusStr = [[[multiArray objectAtIndex:section] objectAtIndex:row] objectForKey:#"status"];
[cell.statusLabel setText:ticketStatusStr];
if([ticketStatusStr isEqualToString:#"Open"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0 green:0.6 blue:0.8 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"In Progress"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:1.0 green:0.733 blue:0.2 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Resolved"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.6 green:0.8 blue:0 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Closed"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1.0]];
}
NSString * categoryStr = [[[multiArray objectAtIndex:section] objectAtIndex:row]objectForKey:#"category"];
[cell.categoryLabel setText:categoryStr];
NSString * titleStr = [[[multiArray objectAtIndex:section] objectAtIndex:row]objectForKey:#"title"];
NSString * userIDStr = [[[multiArray objectAtIndex:section] objectAtIndex:row]objectForKey:#"user_id"];
NSString * handledByStr = [[[multiArray objectAtIndex:section] objectAtIndex:row] objectForKey:#"handled_by"];
[cell.titleLabel setText: [NSString stringWithFormat:#"Title: %#", titleStr]];
[cell.submittedLabel setText: [NSString stringWithFormat:#"Submitted By: %#", userIDStr]];
[cell.handleLabel setText: [NSString stringWithFormat:#"Handled By: %#", handledByStr]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *orignalDate = [dateFormatter dateFromString:[[[[multiArray objectAtIndex:section] objectAtIndex:row]objectForKey:#"date_submitted"] substringToIndex:10]];
[dateFormatter setDateFormat:#"MMMM dd, yyyy"];
NSString * ticketDateStr = [dateFormatter stringFromDate:orignalDate];
[cell.dateLabel setText:ticketDateStr];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
if (count == 1) {
return cell1;
}
return cell;
}
I load a nib for each cell then update the information there. Example:
[cell.statusLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.statusLabel setTextColor:[UIColor whiteColor]];
However I'm having difficulty calling each cell and then updating it from another function it. Is this possible?
I think what you need it to call
HelpDeskCell *cell = (HelpDeskCell *)[self.tableView cellForRowAtIndexPath:#someIndexPath#];
in your other function. Assuming you know which ticket/cell you want to update and then call
cell.statusLabel.text = #"Hello World";
or any other update you want to make
I am new in iOS developer. When I run the the app than time iI
but I will get this type of output.
Here is my code
- (void) iterateItems:(NSArray*) array
{
level++;
for (int i = 0; i < [array count]; i++)
{
commentInfo = [array objectAtIndex:i];
//NSLog(#"data=%#",commentInfo);
Item *item = [[Item alloc] init];
item.Id = [[[commentInfo objectForKey:#"sub_items"]objectAtIndex:0]objectForKey:#"name"];
item.parentId = [[[commentInfo objectForKey:#"sub_items"]objectAtIndex:0]objectForKey:#"name"];
if (item.level == 0)
{
item.title =[commentInfo objectForKey:#"dates"];
item.title1 =[commentInfo objectForKey:#"id"];
}
else
{
item.title=#"abc";
}
//NSLog(#"title is=%#",[commentInfo objectForKey:#"status"]);
item.level = level;
item.visibility = #"normal";
item.childVisibility = #"normal";
[items addObject:item];
[self iterateItems:[commentInfo objectForKey:#"sub_items"]];
}
level--;
}
- (float) cellHeightForRow:(int) row
{
Item *item = [items objectAtIndex:row];
if ([item.visibility isEqualToString:#"hidden"])
{
return 0.0f;
}
else
{
return 50.0f;
}
}
- (void) hideCompleteNode:(UISwipeGestureRecognizer*) gestureRecognizer
{
UITableViewCell *cell = (UITableViewCell*) [[gestureRecognizer view] superview];
NSIndexPath *indexPath = [self.tblView indexPathForCell:cell];
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
if ([item.childVisibility isEqualToString:#"normal"])
{
[self hideChilds:indexPath];
}
}
else
{
int prevIndex = indexPath.row-1;
if (prevIndex >= 0)
{
Item *parentItem = [items objectAtIndex:prevIndex];
while (parentItem.level != 0)
{
prevIndex--;
if (prevIndex >= 0)
parentItem = [items objectAtIndex:prevIndex];
else
break;
}
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:prevIndex inSection:0];
[self hideChilds:indexPath];
}
}
- (void) hideChilds:(NSIndexPath*) indexPath
{
NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithObjects:indexPath, nil];
Item *item = [items objectAtIndex:indexPath.row];
BOOL shouldHide = [item.childVisibility isEqualToString:#"hidden"]?NO:YES;
item.childVisibility = shouldHide?#"hidden":#"normal";
int nextIndex = indexPath.row+1;
if (nextIndex < [items count])
{
Item *childItem = [items objectAtIndex:nextIndex];
while (childItem.level > item.level)
{
childItem.visibility = shouldHide?#"hidden":#"normal";
childItem.childVisibility = shouldHide?#"hidden":#"normal";
[indexPaths addObject:[NSIndexPath indexPathForRow:nextIndex inSection:0]];
nextIndex++;
if (nextIndex < [items count])
childItem = [items objectAtIndex:nextIndex];
else
break;
}
}
[self.tblView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
}
#pragma mark -
#pragma mark - UITableView Datasource and Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self cellHeightForRow:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"itemCell";
UITableViewCell *cell = [self.tblView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
UIImageView *arrowImgView = [[UIImageView alloc] init];
[arrowImgView setBackgroundColor:[UIColor clearColor]];
[arrowImgView setTag:1];
[cell.contentView addSubview:arrowImgView];
UILabel *titleLbl = [[UILabel alloc] init];
[titleLbl setFont:[UIFont fontWithName:#"HelveticaNeue" size:13.0f]];
[titleLbl setTextColor:[UIColor blackColor]];
titleLbl.textAlignment = NSTextAlignmentCenter;
[titleLbl setTag:2];
[titleLbl setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:titleLbl];
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(hideCompleteNode:)];
[swipeGesture setDirection:UISwipeGestureRecognizerDirectionLeft];
[cell.contentView addGestureRecognizer:swipeGesture];
}
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
[cell.contentView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"cell_background.png"]]];
}
else
{
[cell.contentView setBackgroundColor:[UIColor clearColor]];
}
UIImageView *arrowImgView = (UIImageView*) [cell viewWithTag:1];
UILabel *titleLbl = (UILabel*) [cell viewWithTag:2];
if ([item.visibility isEqualToString:#"hidden"])
{
[titleLbl setFrame:CGRectZero];
[arrowImgView setFrame:CGRectZero];
}
else
{
[arrowImgView setFrame:CGRectMake(5.0f+(20.0f*item.level), 20.0f, 10.0f, 10.0f)];
if ([item.childVisibility isEqualToString:#"hidden"])
{
[arrowImgView setImage:[UIImage imageNamed:#"closeArrow"]];
}
else
{
[arrowImgView setImage:[UIImage imageNamed:#"openArrow"]];
}
[titleLbl setFrame:CGRectMake(20.0f+(20.0f*item.level), 10.0f, 320.0f - (20.0f+(20.0f*item.level)), 30.0f)];
[titleLbl setText:item.title];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.layer.shadowOpacity = 0.3;
cell.layer.shadowColor = [UIColor blueColor].CGColor;
cell.layer.shadowOffset = CGSizeMake(0.0, 4);
[tblView setSeparatorColor:[UIColor redColor]];
tblView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
[tblView setSeparatorColor:[UIColor blackColor]];
tblView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
// [self hideChilds:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[self.tblView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithRed:0.004 green:0.482 blue:0.776 alpha:1];
[self hideChilds:indexPath];
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
}
else
{
Item *item = [items objectAtIndex:indexPath.row];
NSLog(#"value=%#",[NSString stringWithFormat:#"%#",item.title1]);
approveleaseoffer *secondViewController =
[self.storyboard instantiateViewControllerWithIdentifier:#"approveleaseofferpage"];
secondViewController.offer_number=[NSString stringWithFormat:#"%#",item.title1];
[self.navigationController pushViewController:secondViewController animated:YES];
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:#selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
-(void)viewDidLayoutSubviews
{
if ([tblView respondsToSelector:#selector(setSeparatorInset:)]) {
[tblView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tblView respondsToSelector:#selector(setLayoutMargins:)]) {
[tblView setLayoutMargins:UIEdgeInsetsZero];
}
}
Try changing the line item.childVisibility = #"normal"; to item.childVisibility = #"hidden";
in iterateItems method.
I am creating multiple lists like questions and answer session, question with multiple answers in table rows. But whenever I select a row other questions answers are also get selected and when I came back to same all the selections are gone. So how to avoid this ? Please help.
my code is,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(val==1)
{
checkedArr=[[NSMutableArray alloc] init];
for (int i = 0; i<17; i++)
{
[checkedArr addObject:#"1"];
}
NSLog(#"Checked arr size %i",[checkedArr count]);
return 17;
}
else if(val==2)
{
checkedArr=[[NSMutableArray alloc] init];
for (int i = 0; i<13; i++)
{
[checkedArr addObject:#"1"];
}
return 13;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%i",indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18.0];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:99/255.0f green:209/255.0f blue:248/255.0f alpha:1.0];
cell.selectedBackgroundView = selectionColor;
if([[checkedArr objectAtIndex:indexPath.row] isEqual:#"0"])
{
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]];
[checkedArr addObject:indexPath];
NSLog(#"checkedArr 0000000");
}
else if ([[checkedArr objectAtIndex:indexPath.row] isEqual:#"1"])
{
cell.accessoryView.hidden=TRUE;
//cell.accessoryView=Nil;
[checkedArr removeObject:indexPath];
NSLog(#"checkedArr 111111");
}
cell.textLabel.frame=CGRectMake(75.0, 50.0, 150.0, 20.0);
cell.textLabel.text=[listArray objectAtIndex:indexPath.row];
NSLog(#"Checked arr size %i",[checkedArr count]);
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
cell=[questionTable cellForRowAtIndexPath:indexPath];
[checkedArr replaceObjectAtIndex:indexPath.row withObject:#"0"];
if([[checkedArr objectAtIndex:indexPath.row] isEqual:#"0"])
{
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]];
[checkedArr addObject:indexPath];
NSLog(#"checkedArr 0000000");
}
else if ([[checkedArr objectAtIndex:indexPath.row] isEqual:#"1"])
{
cell.accessoryView=nil;
[checkedArr removeObject:indexPath];
NSLog(#"checkedArr 111111");
}
[questionTable deselectRowAtIndexPath:indexPath animated:YES];
//[self.questionTable reloadData];
NSLog(#"Val is %i",val);
NSLog(#"selected is %#",[listArray objectAtIndex:indexPath.row]);
// NSLog(#"Checked arr descripton %#",[checkedArr description]);
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.accessoryView = nil;
}
When using reloading with indexpaths or indexsets the _recordLabel and _dateLabel are shown, and then not shown, and it repeats again. Im using the debug paint layers and its nowhere around. But if use reload data everything seems fine. I don't know why is that happening.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier;
cellIdentifier = [_sections objectAtIndex:indexPath.section];
XFitGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[XFitGroupCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[self stampCell:cell atIndexPath:indexPath];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)stampCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
if ([cell.reuseIdentifier isEqualToString:#"exerciseDescriptionCell"]) {
if (!_textView) {
_textView = [[UITextView alloc] initWithFrame:CGRectMake(0.f, 22.f, cell.frame.size.width, 66.f)];
}
_textView.editable = NO;
_textView.font = [UIFont fontWithName:#"Avenir-Light" size:14.f];
[cell.contentView addSubview:_textView];
}
else if ([cell.reuseIdentifier isEqualToString:#"exerciseResultsCell"]) {
UILabel *recordLabelTag = [[UILabel alloc] initWithFrame:CGRectMake(10.f, 28.f, 55.f, 14.f)];
if ([_exercise.eType.name isEqualToString:#"Strength"]) {
recordLabelTag.text = #"PR";
}
else {
recordLabelTag.text = #"UB";
}
recordLabelTag.font = [UIFont fontWithName:#"Avenir-Heavy" size:14.f];
recordLabelTag.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:recordLabelTag];
if (!_recordLabel) {
_recordLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.f, 48.f, 55.f, 12.f)];
}
_recordLabel.font = [UIFont fontWithName:#"Avenir-Light" size:12.f];
_recordLabel.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:_recordLabel];
UILabel *dateLabelTag = [[UILabel alloc] initWithFrame:CGRectMake(70.f, 28.f, 55.f, 14.f)];
dateLabelTag.text = #"Date";
dateLabelTag.font = [UIFont fontWithName:#"Avenir-Heavy" size:14.f];
dateLabelTag.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:dateLabelTag];
if (!_dateLabel) {
_dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(70.f, 48.f, 55.f, 12.f)];
}
_dateLabel.font = [UIFont fontWithName:#"Avenir-Light" size:12.f];
_dateLabel.textAlignment = NSTextAlignmentCenter;
[cell.contentView addSubview:_dateLabel];
UIButton *recordButton = [[UIButton alloc] initWithFrame:CGRectMake(cell.frame.size.width - 73.f, 30.f, 65.f, 28.f)];
recordButton.backgroundColor = [UIColor colorWithRed:77.f/255.f green:123.f/255.f blue:209.f/255.f alpha:1.f];
recordButton.layer.cornerRadius = 4.f;
[recordButton addTarget:self action:#selector(addRecord) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:recordButton];
UILabel *newPRLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.f, 7.f, 55.f, 14.f)];
if ([_exercise.eType.name isEqualToString:#"Strength"]) {
newPRLabel.text = #"New PR";
}
else {
newPRLabel.text = #"New UB";
}
newPRLabel.textColor = [UIColor whiteColor];
newPRLabel.font = [UIFont fontWithName:#"Avenir-Book" size:14.f];
[recordButton addSubview:newPRLabel];
UIButton *showAllButton = [[UIButton alloc] initWithFrame:CGRectMake(cell.frame.size.width - 73.f - 75.f, 30.f, 65.f, 28.f)];
showAllButton.backgroundColor = [UIColor colorWithRed:98.f/255.f green:233.f/255.f blue:126.f/255.f alpha:1.f];
showAllButton.layer.cornerRadius = 4.f;
[cell.contentView addSubview:showAllButton];
UILabel *showAllLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.f, 7.f, 55.f, 14.f)];
showAllLabel.text = #"Show All";
showAllLabel.textColor = [UIColor whiteColor];
showAllLabel.font = [UIFont fontWithName:#"Avenir-Book" size:14.f];
[showAllButton addSubview:showAllLabel];
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
if ([cell.reuseIdentifier isEqualToString:#"exerciseDescriptionCell"]) {
[(XFitGroupCell *)cell setText:#"Description"];
[(XFitGroupCell *)cell setImage:[UIImage imageNamed:#"descriptionIcon"]];
_textView.text = _exercise.overview;
}
else if ([cell.reuseIdentifier isEqualToString:#"exerciseResultsCell"]) {
[(XFitGroupCell *)cell setText:#"Previous Results"];
[(XFitGroupCell *)cell setImage:[UIImage imageNamed:#"recordIcon"]];
ExerciseRecord *personalRecord = _exercise.personalRecord;
NSLog(#"Received: %#\n", personalRecord.score);
_recordLabel.text = [personalRecord.score stringValue];
NSLog(#"Text : %#\n", _recordLabel.text);
_dateLabel.text = [_dateFormatter stringFromDate:personalRecord.date];
}
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
return 88.f;
}
else if (indexPath.section == 1) {
return 66.f;
}
return 0.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 15.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 7.f;
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1) {
if (buttonIndex == 1) {
ExerciseRecord *eRecord = [NSEntityDescription insertNewObjectForEntityForName:#"ExerciseRecord" inManagedObjectContext:_managedObjectContext];
eRecord.score = [NSNumber numberWithInt:[[alertView textFieldAtIndex:0].text intValue]];
eRecord.date = [NSDate date];
eRecord.exercise = _exercise;
NSError *error;
if (![_managedObjectContext save:&error]) {
NSLog(#"%# %#", error, [error userInfo]);
abort();
}
[_tableView reloadData];
//[_tableView beginUpdates];
//[_tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
//[_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
//[_tableView endUpdates];
}
}
}
I am not sure why this isn't working, but from my experience I'd recommend you use a framework while working with Core Data instead of doing all the work manually yourself. I personally use the Sensible TableView framework, which automatically fetches my data and displays it in table views. It also handles all entity relationships and auto creates the detail views for them. Saves me tons of development time when working on Core Data projects. HTH.
I'm have kind of a really small and annoying problem. (No pun intended)
I kind seem to find my mistake. I also asked in chat, but we couldn't find the solution. I got the "Load more..." for my tableView from Abizerns github and implemented it. It works, except for the part, that when it starts up I have to click "Load more...". So on start it doesn't show me the first entries of the tableView until I clicked on "Load more...". You can see my annoyance. Maybe someone can spot my mistake, so that the tableView actually loads the first ten entries on start up.
#define kNumberOfItemsToAdd 10
#define PADDING 10.0f
#interface Main ()
#end
#implementation Main
#synthesize tabelle;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
numberOfItemsToDisplay = kNumberOfItemsToAdd;
return self;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (numberOfItemsToDisplay == [tabelle count]) {
return 1;
}
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return numberOfItemsToDisplay;
} else {
return 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 6;
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 1;
}
if (indexPath.section == 0) {
cell.textLabel.font = [UIFont fontWithName:#"Verdana" size:14.0];
cell.detailTextLabel.font = [UIFont fontWithName:#"Verdana" size:12.0];
NSString *TableText = [[NSString alloc] initWithFormat:#"%#", [[tabelle objectAtIndex:indexPath.row] Name]];
NSString *TableText2 = [[NSString alloc] initWithFormat:#"%#", [[tabelle objectAtIndex:indexPath.row] m_m]];
NSString *cellValue = [NSString stringWithFormat:#"%#", TableText2];
NSString *cellValue2 = [NSString stringWithFormat:#"by: %#", TableText];
cell.textLabel.text = cellValue;
cell.detailTextLabel.textColor = [UIColor colorWithRed:0.196f green:0.3098f blue:0.52f alpha:1.f];
cell.detailTextLabel.text = cellValue2;
} else {
cell.textLabel.text = [NSString stringWithFormat:#"Next %d items", kNumberOfItemsToAdd];
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.textColor = [UIColor colorWithRed:0.196f green:0.3098f blue:0.52f alpha:1.f];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.f];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [[self.tabelle objectAtIndex:indexPath.row] m_m];
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];
return textSize.height + PADDING * 3;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1) {
NSUInteger i, totalNumberOfItems = [tabelle count];
NSUInteger newNumberOfItemsToDisplay = MIN(totalNumberOfItems, numberOfItemsToDisplay + kNumberOfItemsToAdd);
NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
for (i=numberOfItemsToDisplay; i<newNumberOfItemsToDisplay; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
numberOfItemsToDisplay = newNumberOfItemsToDisplay;
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
if (numberOfItemsToDisplay == totalNumberOfItems) {
[tableView deleteSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationTop];
}
[tableView endUpdates];
// Scroll the cell to the top of the table
if (newNumberOfItemsToDisplay < totalNumberOfItems) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200000000), dispatch_get_main_queue(), ^(void){
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
});
[tableView deselectRowAtIndexPath:indexPath animated:YES];
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200000000), dispatch_get_main_queue(), ^(void){
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:totalNumberOfItems-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
});
}
}
}
I haven't used a "Load more..." implementation, but maybe what you need is add [self.tabelle reloadData] in your - (void)viewWillAppear:(BOOL)animated method.
What method gets called when you click "Load more..."? Can you not programmatically call that method when the tableview is loaded?