in tableview how dynamically changing section y position ios - ios

The Screen Shot I added here i have dynamic data in my sections. Each section have one row and have label and values in it . my problem is when i add or change count of values its sections 'y' margin changes. please help me if anyone Know
here is my code
- (UIView *)tableView:(UITableView *)tableView1 viewForHeaderInSection:(NSInteger)section{
UIView *section1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView1.bounds.size.width, tableView1.bounds.size.height)] ;
[section1 setBackgroundColor:[UIColor clearColor]];
return section1;
}
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
if(section !=0){
return 22;
}
return 0.0;
}
-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
return 0.0;
}
//dynamic decide no of sections in table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(tagLastbutton == lastRow){
lastRow = lastRow +1;
return lastRow;
}
return lastRow;
//[self.arrayObjects count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
// Return YES to allow the user to reorder table view rows
//
- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return NO;
}
// Return a cell containing the text to display at the provided row index.
//changing background according to input
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MyuSocialNetworkCell";
CreateNewProfileViewCell * cell = (CreateNewProfileViewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nibObjects= [[NSBundle mainBundle] loadNibNamed:#"CreateNewProfileViewCell" owner:nil options:nil];
for(id currentObject in nibObjects)
{
if([currentObject isKindOfClass:[CreateNewProfileViewCell class]])
{
cell = (CreateNewProfileViewCell *) currentObject;
break;
}
}
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//[indexPath.row color]
// if([self.subCategoryString length] != 0){
// cell.addFoodAllergyLabel.text = self.subCategoryString;
// }
NSString *str;
if(indexPath.section < [self.namesFoodSubCategoryLabels count]){
str = [self.namesFoodSubCategoryLabels objectAtIndex:indexPath.section];
}
int len=str.length;
NSLog(#"Ch ###########################%u",len);
len=floor(len/29);
NSLog(#"Ch ##After Row##################%u",len);
len++;
// len++;
/*
CGRect frameCell = CGRectMake(cell.frame.origin.x, cell.frame.origin.y+newCellPosition, cell.frame.size.width, cell.frame.size.height);
cell.frame = frameCell;
*/
CGRect frame = CGRectMake(cell.addFoodAllergyLabel.frame.origin.x, cell.addFoodAllergyLabel.frame.origin.y, cell.addFoodAllergyLabel.frame.size.width, cell.addFoodAllergyLabel.frame.size.height*len);
cell.addFoodAllergyLabel.numberOfLines = len;
cell.addFoodAllergyLabel.frame = frame;
CGRect frameMidBox = CGRectMake(cell.midMainRowBoxImageView.frame.origin.x, cell.midMainRowBoxImageView.frame.origin.y, cell.midMainRowBoxImageView.frame.size.width, cell.midMainRowBoxImageView.frame.size.height*len);
cell.midMainRowBoxImageView.frame = frameMidBox;
CGRect frameLowerCornerBox = CGRectMake(cell.lowerRowCornerImageView.frame.origin.x, cell.lowerRowCornerImageView.frame.origin.y+((len*26)-26), cell.lowerRowCornerImageView.frame.size.width, cell.lowerRowCornerImageView.frame.size.height);
newCellPosition = cell.lowerRowCornerImageView.frame.origin.y+22;
cell.lowerRowCornerImageView.frame = frameLowerCornerBox;
CGRect frameButtonImage = CGRectMake(cell.addFoodAllergyButton.frame.origin.x, cell.addFoodAllergyButton.frame.origin.y+((len * 13)-13), cell.addFoodAllergyButton.frame.size.width, cell.addFoodAllergyButton.frame.size.height);
cell.addFoodAllergyButton.frame = frameButtonImage;
cell.addFoodCategoryImageView.frame = frameButtonImage;
NSLog(#"Array&&&&&&&&&&&&&&&&%#",self.namesFoodSubCategoryLabels);
NSLog(#"indexPath.row %u",indexPath.row);
if(indexPath.section < [self.namesFoodSubCategoryLabels count]){
cell.addFoodAllergyLabel.text = [self.namesFoodSubCategoryLabels objectAtIndex:indexPath.section];
cell.addFoodCategoryImageView.image = [UIImage imageNamed:[self.imagesFoodCategories objectAtIndex:indexPath.section]];
}
//CGRect frame = CGRectMake(0, 0, 60, 60);
//cell.frame=frame;
cell.addFoodAllergyButton.tag = indexPath.section+1;
cell.addFoodAllergyLabel.tag = indexPath.section+1;
[cell.addFoodAllergyButton addTarget:self action:#selector(addFoodAllergyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
-(CGFloat) tableView:(UITableView *) tableView1 heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
for(int i=0 ; i< [self.namesFoodSubCategoryLabels count] ; i++){
NSString *str = [self.namesFoodSubCategoryLabels objectAtIndex:i];
int len=str.length;
NSLog(#"Ch ######heightForRow#####################%u",len);
len=floor(len/29);
len++;
//len++;
NSLog(#"Ch ##After heightForRow###################%u",len);
return ((len*26)+11);
}
return 37;
}
I am changing dynamically background,label and section height but not able to handle sections y dynamically. so as screenshots shows that my problem is to manage sections margin in y position which is change between every two sections.

You can change the value of section on the basis of some condition like
if(section==0)
then "section1"
if(section==1)
then "section2"
because section starts from 0,1,2,3,4,5,6......n

Related

Calculate UITableViewCell height with UIWebview in iOS

I am creating a table based application where need to display one UIWebView for each table cell. I have tried by keeping a NSMutableArray of height for each cell in my table, but it's not working.
here is my code :
- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
aWebView.scrollView.scrollEnabled = NO;
CGRect frame = aWebView.frame;
frame.size.height = 1;
aWebView.frame = frame;
CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
aWebView.frame = frame;
if (arrayRowHeights.count == 0 || arrayRowHeights == nil) {
arrayRowHeights = [[NSMutableArray alloc] init];
[arrayRowHeights addObject:[NSString stringWithFormat:#"%f", fittingSize.height]];
}
else{
[arrayRowHeights addObject:[NSString stringWithFormat:#"%f", fittingSize.height]];
if (arrayRowHeights.count == aWebView.tag) {
[tblEventInfo reloadData];
}
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrayEventInfo count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [[arrayRowHeights objectAtIndex:indexPath.section] floatValue];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
EventInfoDetail *event = [[EventInfoDetail alloc] init];
event = [arrayEventInfo objectAtIndex:indexPath.section];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
webViewHTML = [[UIWebView alloc]init];
webViewHTML.delegate = self;
webViewHTML.tag = arrayEventInfo.count;
webViewHTML.backgroundColor = [UIColor clearColor];
webViewHTML.opaque = NO;
webViewHTML.userInteractionEnabled = NO;
if (event.d_description == (NSString *)[NSNull null]){
[webViewHTML loadHTMLString:#"" baseURL: nil];
}
else{
[webViewHTML loadHTMLString:event.d_description baseURL: nil];
}
webViewHTML.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
[cell.contentView addSubview:webViewHTML];
}
return cell;
}
My problem is I am not able to set the the height of the cell properly, can anyone please figure out where is my mistake on this given code. Thanks!
Your webViewDidFinishLoad for each cell will get called only after the tablecell is loaded i,e; So the sequence calls will be
heightForRowAtIndexPath -> cellForRowAtIndexPath -> webViewDidFinishLoad . So you will never be able to set the height before cell loads. After webView is loaded try calling
- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{[tableView reloadRowsAtIndexPaths:[tableView indexPathsForVisibleRows]
withRowAnimation:UITableViewRowAnimationNone];}
which will call heightForRowAtIndexPath again and try to set it again.
But the height will increase at runtime .You should customize that event
Initialize your arrayRowHeights as NSMutableArray beforehand(in viewDidLoad method for instance) with the same capacity as arrayEventInfo.Change your webView delegate method to this one
- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
CGFloat height = aWebView.scrollView.contentSize.height;
if (height != [[arrayRowHeights objectAtIndex: aWebView.tag] floatValue]) {
[arrayRowHeights insertObject:[NSNumber numberWithFloat: height] atIndex: aWebView.tag];
[tblEventInfo reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForItem:0 inSection:aWebView.tag]] withRowAnimation:UITableViewRowAnimationNone];
}
}
In method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Change line
webViewHTML.tag = arrayEventInfo.count;
with line
webViewHTML.tag = indexPath.section;

How to create multiple column in an one row UITableViewCell in swift?

How to Create multiple column in an one row.
Like this image!. https://pbs.twimg.com/media/CEuO0hUUUAARX_L.png !
You can also use gridview for your requirement like GMGridView or UIGridView
Check below sample code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellIdentifier = #"gridCell";
UITableViewCell *gridCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(gridCell == nil)
{
gridCell = [[[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIdentifier] autorelease];
gridCell.accessoryType = UITableViewCellAccessoryNone;
gridCell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSArray* items = [_grids objectAtIndex:indexPath.section];
int imageIndex = 0;
int yOffset = 0;
while (imageIndex < items.count)
{
int yPos = 4 + yOffset * 74;
for(int i = 0; i < 4; ++i)
{
CGRect rect = CGRectMake((18 + i * 80), yPos, 40, 40);
UIImageView* imageView = [self gridImageRect:rect forImage:[items objectAtIndex:imageIndex]];
[gridCell.contentView addSubview:imageView];
[imageView release];
rect = CGRectMake(((80 * i)-4), (yPos+44), 80, 12);
UILabel* label = [self descriptionOfImage:imageIndex inRect:rect];
[gridCell.contentView addSubview:label];
[label release];
++imageIndex;
}
++yOffset;
}
return gridCell;
}

How to populate, Expandable TableView with two NSMutableArray using objective-c

I am using an Expandable UITableview created by Tom Fewster. I want to tweak the example using two NSMutableArrays, which is a scenario whereby if someone wants to populate an expandable/collapse treeview table from webservice json data would want to achieve. So since in his example the GroupCell does not have an array of, I am wondering how can I do it? Please bear in mind that my Objective-C is still rusty hence, I'm asking this question.
With my attempt is only displaying the first ObjectAtIndex:indexPath:0 for the group.
I want to be able to populate the table and get output like this;
Group A
Row 1a
Row 2a
Row 3a
Group B
Row 1b
Row 2b
Group C
Row 1c
Row 2c
Row 3c
and so on.
You may use JSON data as well to explain your answer if you understand it better that way.
Here i want to populate the table with JSON data so the GroupCell show class_name and rowCell show subject_name. This is the console of what I am parsing from the JSON web-service;
(
{
"class_id" = 70;
"class_name" = Kano;
subject = (
"subject_id" = 159;
"subject_name" = "Kano Class";
}
);
},
{
"alarm_cnt" = 0;
"class_id" = 71;
"class_name" = Lagos;
subject = (
"subject_id" = 160;
"subject_name" = "Lagos Class";
}
);
},
{
"alarm_cnt" = 3;
"class_id" = 73;
"class_name" = Nasarawa;
subject = (
"subject_id" = 208;
"subject_name" = "DOMA Class";
},
"subject_id" = 207;
"subject_name" = "EGGON Class";
},
"subject_id" = 206;
"subject_name" = "KARU Class";
},
"subject_id" = 209;
"subject_name" = "LAFIA Class";
},
"subject_id" = 161;
"subject_name" = "Nasarawa State Class";
}
);
},
{
"alarm_cnt" = 2;
"class_id" = 72;
"class_name" = Rivers;
subject = (
"subject_id" = 162;
"subject_name" = "Rivers Class";
}
);
}
)
I have tried this here is my snippet
- (UITableViewCell *)tableView:(ExpandableTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"RowCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *d=[_sitesJson objectAtIndex:0] ;
NSArray *arr=[d valueForKey:#"subject_name"];
NSDictionary *subitems = [arr objectAtIndex:0];
NSLog(#"Subitems: %#", subitems);
NSString *siteName = [NSString stringWithFormat:#"%#",subitems];
cell.textLabel.text =siteName;
//}
NSLog(#"Row Cell: %#", cell.textLabel.text);
// just change the cells background color to indicate group separation
cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
cell.backgroundView.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:243.0/255.0 blue:1.0 alpha:1.0];
return cell;
}
- (UITableViewCell *)tableView:(ExpandableTableView *)tableView cellForGroupInSection:(NSUInteger)section
{
static NSString *CellIdentifier = #"GroupCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *textLabel = (UILabel *)[cell viewWithTag:2];
NSDictionary *d2 = [_regionsJson objectAtIndex:0];
NSArray *arr2 = [d2 objectForKey:#"class_name"];
NSString *regions = [[arr2 objectAtIndex:section]objectAtIndex:0];
textLabel.textColor = [UIColor whiteColor];
textLabel.text = [NSString stringWithFormat: #"%# (%d)", regions, (int)[self tableView:tableView numberOfRowsInSection:section]];
NSLog(#"Group cell label: %#", textLabel.text);
// We add a custom accessory view to indicate expanded and colapsed sections
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ExpandableAccessoryView"] highlightedImage:[UIImage imageNamed:#"ExpandableAccessoryView"]];
UIView *accessoryView = cell.accessoryView;
if ([[tableView indexesForExpandedSections] containsIndex:section]) {
accessoryView.transform = CGAffineTransformMakeRotation(M_PI);
} else {
accessoryView.transform = CGAffineTransformMakeRotation(0);
}
return cell;
}
He, just need to update one single method little bit way
- (UITableViewCell *)tableView:(ExpandableTableView *)tableView cellForGroupInSection:(NSUInteger)section
{
static NSString *CellIdentifier = #"GroupCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSIndexPath *indexPath;
NSString *regions = [[_dataGroup objectAtIndex:section]objectAtIndex:0];
cell.textLabel.text = [NSString stringWithFormat: #"%# ", regions];
// We add a custom accessory view to indicate expanded and colapsed sections
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ExpandableAccessoryView"] highlightedImage:[UIImage imageNamed:#"ExpandableAccessoryView"]];
UIView *accessoryView = cell.accessoryView;
if ([[tableView indexesForExpandedSections] containsIndex:section]) {
accessoryView.transform = CGAffineTransformMakeRotation(M_PI);
} else {
accessoryView.transform = CGAffineTransformMakeRotation(0);
}
return cell;
}
May help it you.
HTH, Enjoy Coding !!
I think you need to create a TableView which will have a sections array, and each sections row will be populated using the corresponding sections array. Tapping on a section will expand it and it's all rows will be visible.
To meet your requirements, you could follow the below steps as well -
1) Your modal should have a array for sections. The sections array will contain the sections objects, name of the section and corresponding array of the rows.
2) Implement the data source methods of the table view like
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [section count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50; // sections height
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return nil;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0 , 0, tableView.frame.size.width , 50)] autorelease];
[view setBackgroundColor:[UIColor redColor]];
view.layer.masksToBounds = YES;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5 , 2 , view.frame.size.width - 10 , view.frame.size.height - 3)];
label.text = ((SectionObject *)[section objectAtIndex:indexPath.section]).sectionName;
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentLeft;
label.textColor = [UIColor WwhiteColor];
label.clipsToBounds = YES;
label.font = [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:14.0f];
label.layer.masksToBounds = YES;
UIImageView *arrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(view.frame.size.width - 30, 0, 17 , 17)];
[arrowImage setCenter:CGPointMake(arrowImage.center.x , (view.frame.size.height/2) ) ];
if(section == self.m_currentSelectedSection)
[arrowImage setImage:self.m_upArrowImage];
else
[arrowImage setImage:self.m_downArrowImage];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)];
button.tag = section;
[button addTarget:self action:#selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
[view addSubview:label];
[label release];
[view addSubview:arrowImage];
[arrowImage release];
[view addSubview:button];
[button release];
view.clipsToBounds = YES;
return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = 0;
if(self.m_currentSelectedSection == section)
count = [((SectionObject *)[section objectAtIndex:indexPath.section]).rowArray count];
return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40.0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * cellId = #"cellIdentifier";
UITableViewCell *cell = nil;
cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:cellId];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
//customize cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
When ever any section will be tapped following event will be invoked
- (void) sectionTapped:(UIButton *)button
{
self.m_currentSelectedSection = button.tag;
[self performSelector:#selector(refreshView) withObject:nil afterDelay:POINT_ONE_SECOND];
if(m_winnerSlotList->at(self.m_currentSelectedSection).m_leaderboardList.size())
[self.m_leaderboardTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:button.tag] atScrollPosition:UITableViewScrollPositionTop animated:YES];
UIView *baseView = [button superview];
if(baseView)
{
for(int ii = 0 ; ii < [[baseView subviews] count] ; ii++ )
{
UIView *anyView = [[baseView subviews] objectAtIndex:ii];
if([anyView isKindOfClass:[UIImageView class]])
[(UIImageView *)anyView setImage:self.m_upArrowImage];
}
}
}
Initialize self.m_currentSelectedSection = 0, for the first time, this will show the rows for 0th section. As any section is tapped it's rows will be visible (corresponding section rows will expand) and the rows for the previous selected section will be hidden(previous section rows will collapse).
If you need to show more than one section as expanded than you need to keep track of all the section whether a section is expanded or not and accordingly load show/ hide the cells for the corresponding section.

UITableViewCell indexPath.section issue on iPad

I am trying to add an image next to the cell text in the 8th row. My issue is that it doesn't entering inside (indexPath.row == 9) method while I have put breakpoint I get this value from indexPath.row = {length = 2, path = 0 - 0}. So please where would be my issue?
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (!cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:#"cell"] autorelease];
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"bakiyem-cell-bg.png"]];
img.x = 10.;
img.y = -6.;
[cell.contentView addSubview:img];
[img release];
//
cell.textLabel.font = [Constants regularFontWithSize:24.];
cell.textLabel.textColor = [Constants textGrayColor];
cell.detailTextLabel.font = [Constants mediumFontWithSize:24.];
}
cell.detailTextLabel.textColor = indexPath.row == 4 ? [UIColor colorWithRed:218./255. green:0 blue:37./255. alpha:1] : [Constants textGrayColor];
//My issue
if (indexPath.row == 9) {
cell.imageView.image = [UIImage imageNamed:#"info-logo.png"];
}
//
NSDictionary *dic = [data objectAtIndex:indexPath.row];
cell.textLabel.text = [dic objectForKey:#"value1"];
cell.detailTextLabel.text = [dic objectForKey:#"value2"];
return cell;
}
It really should be
if (indexPath.row == 7) {
Because you only have one row.
If the break point is still not entering your if statement, then add some more logging around it to see what is going one.
Like how about if you try
NSLog(#"row = %i", indexPath.row);
if (indexPath.row == 7) {
NSLog(#"In if statement for row = %i", indexPath.row);
UIImage *myImage = [UIImage imageNamed:#"info-logo.png"];
NSLog(#"My image=%#",myImage);
cell.imageView.image = myImage;
}
What shows up in NSLog?
The eight row has an index of 7
You probably mean indexPath.row instead of indexPath.section
If you want to customize UITableViewCells, please use custom cells
try it with indexPath.section == 7. Or probably indexPath.row == 7 as Cem has written in the comment.
Do you have 9 rows inside 1 section, or 9 sections and in each section 1 row?
For the first case use:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1 ;
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section==0)
{
return 9;
}
}
For the second case;
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 9 ;
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
Also, in cellForRowAtIndexPath method use:
In the first case: indexPath.row==9
In the second case: indexPath.section==0
You should have atleast 9 rows is data array in the following method and indexPath.row = {length = 2, path = 0 - 0} mean you are in 0th row of 0th section. If you return hard code 9 in number of rows method then it will enter in (indexPath.row == 8)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [data count]; }

Using cached UIView to set cell background view in tableView:willDisplayCell:forRowAtIndexPath:

This is my solution for setting custom grouped table view cell backgrounds:
- (UIView *)top
{
if (_top) {
return _top;
}
_top = [[UIView alloc] init];
[_top setBackgroundColor:[UIColor blueColor]];
return _top;
}
// dot dot dot
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSInteger maxRow = [tableView numberOfRowsInSection:section] - 1;
if (maxRow == 0) {
[cell setBackgroundView:[self lonely]];
} else if (row == 0) {
[cell setBackgroundView:[self top]];
} else if (row == maxRow) {
[cell setBackgroundView:[self bottom]];
} else {
[cell setBackgroundView:[self middle]];
}
}
Obviously it doesn't work as expected which brings me here, but it does work when I don't use cached views:
UIView *background = [[UIView alloc] init];
if (maxRow == 0) {
[background setBackgroundColor:[UIColor redColor]];
} else if (row == 0) {
[background setBackgroundColor:[UIColor blueColor]];
} else if (row == maxRow) {
[background setBackgroundColor:[UIColor yellowColor]];
} else {
[background setBackgroundColor:[UIColor greenColor]];
}
[cell setBackgroundView:background];
UPDATE: After Jonathan pointed out that I can't use the same view for more than one cell, I decided to follow the table view model where it has a queue of reusable cells. For my implementation, I have a queue of reusable background views (_backgroundViewPool):
#implementation RootViewController {
NSMutableSet *_backgroundViewPool;
}
- (id)initWithStyle:(UITableViewStyle)style
{
if (self = [super initWithStyle:style]) {
_backgroundViewPool = [[NSMutableSet alloc] init];
UITableView *tableView = [self tableView];
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
return self;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 6;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0) {
return 1;
}
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[[cell textLabel] setText:[NSString stringWithFormat:#"[%d, %d]", [indexPath section], [indexPath row]]];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *backgroundView = [cell backgroundView];
[_backgroundViewPool addObject:backgroundView];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSInteger maxRow = [tableView numberOfRowsInSection:section] - 1;
UIColor *color = nil;
if (maxRow == 0) {
// single cell
color = [UIColor blueColor];
} else if (row == 0) {
// top cell
color = [UIColor redColor];
} else if (row == maxRow) {
// bottom cell
color = [UIColor greenColor];
} else {
// middle cell
color = [UIColor yellowColor];
}
UIView *backgroundView = nil;
for (UIView *bg in _backgroundViewPool) {
if (color == [bg backgroundColor]) {
backgroundView = bg;
break;
}
}
if (backgroundView) {
[backgroundView retain];
[_backgroundViewPool removeObject:backgroundView];
} else {
backgroundView = [[UIView alloc] init];
[backgroundView setBackgroundColor:color];
}
[cell setBackgroundView:[backgroundView autorelease]];
}
It works except when you scroll really fast. Some of the background views disappear! I suspect the background views are still being used in more than one cell, but I really don't know what's going on because the background views are supposed to be removed from the queue once it's reused making it impossible for the background view to be used in more than one visible cell.
I've been looking into this since I have posted this question. The current solutions for custom background views for grouped table view cells online are unsatisfactory, they don't used cached views. Additionally, I don't want to have use the solution proposed by XJones and jszumski because it's gonna get hairy once reusable custom cells (e.g., text field cell, switch cell, slider cell) are taken into account.
Have you considered using 4 separate cell identifiers for the "lonely, "top", "bottom", and "middle" cases and setting the backgroundView only once when initializing the cell? Doing it that way lets you leverage UITableView's own caching and reuse without having to write an implementation on top of it.
Update: An implementation for a grouped UITableViewController subclass that reuses background views with a minimal number of cell reuse identifiers (Espresso's use case). tableView:willDisplayCell:forRowAtIndexPath: and tableView:didDisplayCell:forRowAtIndexPath: do the heavy lifting to apply or reclaim each background view, and the pooling logic is handled in backgroundViewForStyle:.
typedef NS_ENUM(NSInteger, JSCellBackgroundStyle) {
JSCellBackgroundStyleTop = 0,
JSCellBackgroundStyleMiddle,
JSCellBackgroundStyleBottom,
JSCellBackgroundStyleSolitary
};
#implementation JSMasterViewController {
NSArray *backgroundViewPool;
}
- (void)viewDidLoad {
[super viewDidLoad];
// these mutable arrays will be indexed by JSCellBackgroundStyle values
backgroundViewPool = #[[NSMutableArray array], // for JSCellBackgroundStyleTop
[NSMutableArray array], // for JSCellBackgroundStyleMiddle
[NSMutableArray array], // for JSCellBackgroundStyleBottom
[NSMutableArray array]]; // for JSCellBackgroundStyleSolitary
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 2) {
return 1;
} else if (section == 3) {
return 0;
}
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
static NSString *switchCellIdentifier = #"switchCell";
static NSString *textFieldCellIdentifier = #"fieldCell";
static NSString *textCellIdentifier = #"textCell";
UITableViewCell *cell = nil;
// apply a cached cell type (you would use your own logic to choose types of course)
if (row % 3 == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:switchCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:switchCellIdentifier];
UISwitch *someSwitch = [[UISwitch alloc] init];
cell.accessoryView = someSwitch;
cell.textLabel.text = #"Switch Cell";
}
} else if (row % 3 == 1) {
cell = [tableView dequeueReusableCellWithIdentifier:textFieldCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:textFieldCellIdentifier];
UITextField *someField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
someField.borderStyle = UITextBorderStyleRoundedRect;
cell.accessoryView = someField;
cell.textLabel.text = #"Field Cell";
}
} else {
cell = [tableView dequeueReusableCellWithIdentifier:textCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:textCellIdentifier];
cell.textLabel.text = #"Generic Label Cell";
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.text = [NSString stringWithFormat:#"[%d, %d]", section, row];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
// apply a cached background view
JSCellBackgroundStyle backgroundStyle = [self backgroundStyleForIndexPath:indexPath tableView:tableView];
cell.backgroundView = [self backgroundViewForStyle:backgroundStyle];
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
JSCellBackgroundStyle backgroundStyle = [self backgroundStyleForIndexPath:indexPath tableView:tableView];
NSMutableArray *stylePool = backgroundViewPool[backgroundStyle];
// reclaim the background view for the reuse pool
[cell.backgroundView removeFromSuperview];
if (cell.backgroundView != nil) {
[stylePool addObject:cell.backgroundView];
}
cell.backgroundView = nil; // omitting this line will cause some rows to appear without a background because they try to be in two superviews at once
}
- (JSCellBackgroundStyle)backgroundStyleForIndexPath:(NSIndexPath*)indexPath tableView:(UITableView*)tableView {
NSInteger maxRow = MAX(0, [tableView numberOfRowsInSection:indexPath.section] - 1); // catch the case of a section with 0 rows
if (maxRow == 0) {
return JSCellBackgroundStyleSolitary;
} else if (indexPath.row == 0) {
return JSCellBackgroundStyleTop;
} else if (indexPath.row == maxRow) {
return JSCellBackgroundStyleBottom;
} else {
return JSCellBackgroundStyleMiddle;
}
}
- (UIView*)backgroundViewForStyle:(JSCellBackgroundStyle)style {
NSMutableArray *stylePool = backgroundViewPool[style];
// if we have a reusable view available, remove it from the pool and return it
if ([stylePool count] > 0) {
UIView *reusableView = stylePool[0];
[stylePool removeObject:reusableView];
return reusableView;
// if we don't have any reusable views, make a new one and return it
} else {
UIView *newView = [[UIView alloc] init];
NSLog(#"Created a new view for style %i", style);
switch (style) {
case JSCellBackgroundStyleTop:
newView.backgroundColor = [UIColor blueColor];
break;
case JSCellBackgroundStyleMiddle:
newView.backgroundColor = [UIColor greenColor];
break;
case JSCellBackgroundStyleBottom:
newView.backgroundColor = [UIColor yellowColor];
break;
case JSCellBackgroundStyleSolitary:
newView.backgroundColor = [UIColor redColor];
break;
}
return newView;
}
}
#end
Although you could very easily get away with dumping all views into one reuse pool, it complicates some of the looping logic and this way is easier to comprehend.
First and foremost, I would check why this kind of caching is necessary. If it's a performance problem, I would check that the problem is indeed the views, and not something else like too many blended layers!
Regarding the caching, there are several approaches. At least three come to mind:
For each of the four backgrounds, register an own cell reuse identifier. Then set the background view depending on the reuse identifier.
Use an own cache for the background views, and reuse background views from there.
Use the same class for background views on all cells, and set the content on them only.
The first solution is quite easy to implement, but it holds the risk that the UITableView ends up holding lots of cells for reusing that are not needed. Also, if you need more types of cells, you would have to provide cells for each type/background combination.
While the second solution reuses cell backgrounds, you have to write an own cache for those, and to set/unset backgrounds where necessary.
The third solution only works if the background view can be configured to show the background for the respective cell. It would reuse the content only, not the background views themselves.
Here is an early screenshot of a test for the second solution:
Here is the implementation:
#implementation RootViewController
{
NSMutableDictionary *_backgroundViews;
}
- (void)viewDidLoad
{
_backgroundViews = [NSMutableDictionary dictionary];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return section / 10 + 1;
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundView = nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.backgroundColor = [UIColor clearColor];
if (!cell.backgroundView || ![cell.backgroundView isKindOfClass:[UIImageView class]]) {
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSInteger maxRow = [tableView numberOfRowsInSection:section] - 1;
NSString *imageName = nil;
UIEdgeInsets insets = UIEdgeInsetsZero;
if (maxRow == 0) {
// single cell
imageName = #"singlebackground";
insets = UIEdgeInsetsMake(12, 12, 12, 12);
} else if (row == 0) {
// top cell
imageName = #"topbackground";
insets = UIEdgeInsetsMake(12, 12, 0, 12);
} else if (row == maxRow) {
// bottom cell
imageName = #"bottombackground";
insets = UIEdgeInsetsMake(0, 12, 12, 12);
} else {
// middle cell
imageName = #"middlebackground";
insets = UIEdgeInsetsMake(0, 12, 0, 12);
}
NSMutableSet *backgrounds = [_backgroundViews objectForKey:imageName];
if (backgrounds == nil) {
backgrounds = [NSMutableSet set];
[_backgroundViews setObject:backgrounds forKey:imageName];
}
UIImageView *backgroundView = nil;
for (UIImageView *candidate in backgrounds) {
if (candidate.superview == nil) {
backgroundView = candidate;
break;
}
}
if (backgroundView == nil) {
backgroundView = [[UIImageView alloc] init];
backgroundView.image = [[UIImage imageNamed:imageName] resizableImageWithCapInsets:insets];
backgroundView.backgroundColor = [UIColor whiteColor];
backgroundView.opaque = YES;
}
cell.backgroundView = backgroundView;
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[[cell textLabel] setText:[NSString stringWithFormat:#"[%d, %d]", [indexPath section], [indexPath row]]];
return cell;
}
If you would like to check it out, here are the images I used (non-retina only and too big, but hey, it's only an example):
singlebackground.png:
topbackground.png:
middlebackground.png:
bottombackground.png:
EDIT - using images as a background view
Given your comments on my answer it seems like you want to display images in the background view of your cells. It is not clear if these images are compiled into your app as resources or downloaded from a service. Regardless, you can use the same UIImage instance in multiple UIImageView instances. So as you create your cells, you can create a new UIImageView on the fly for use as the background view and then set the image property to the appropriate UIImage based on the cell's indexPath.
If the images are compiled into your app then [UIImage imageNamed:#""] uses an iOS implemented cache and will perform well. If you are downloading images (presumably on a background thread) then you will need to implement a disk and/or memory cache for your image data.
ORIGINAL ANSWER
When you configure your cell in tableView:cellForRowAtIndexPath: use the cell identifier to use the built-in caching of the tableView to cache cells with the various background views for you.
Something like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *singleCellID = #"single";
static NSString *firstCellID = #"first";
static NSString *middleCellID = #"middle";
static NSString *lastCellID = #"last";
NSString *cellID = nil;
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSInteger maxRow = [tableView numberOfRowsInSection:section] - 1;
UIColor *color = nil;
if (maxRow == 0) {
// single cell
cellID = singleCellID;
} else if (row == 0) {
// top cell
cellID = firstCellID;
} else if (row == maxRow) {
// bottom cell
cellID = lastCellID;
} else {
// middle cell
cellID = middleCellID;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
if (cell == nil) {
if (cellID == singleCellID) {
// create single cell
cell = ...
cell.backgroundView = ...
}
else if (cellID == firstCellID) {
// create first cell
cell = ...
cell.backgroundView = ...
}
else if (cellID == lastCellID) {
// create last cell
cell = ...
cell.backgroundView = ...
}
else {
// create middle cell
cell = ...
cell.backgroundView = ...
}
}
}
[EDIT]
Ok, so, as far as you use custom background view, I think you should assign your background view to cell's .backgroundView property in the tableView:cellForRowAtIndexPath: method and do not use your own views caching mechanism, because table view caches entire cell with all it's subviews - you assign background view when you create cell and later just update it's backgroundColor with proper value (in your case, based on index path).
Also, this is just a suggestion, your background view might be obscured with cell's other content (e.g. you added something to .contentView) - try setting cell / contentView .alpha value to 0.5 to be able to see through it. Code is still related - this method is called every time UITableView needs new cell to display on the screen
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = nil;
static NSString* identifer = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:identifer];
if(cell==nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
cell.backgroundView = [YourCustomView new];//assign your custom background view here
}
cell.textLabel.text = [NSString stringWithFormat:#"%d",indexPath.row];
//update background view's color based on index path row
if(indexPath.row==0)
cell.backgroundView.backgroundColor = [UIColor redColor];
else if(indexPath.row==1)
cell.backgroundView.backgroundColor = [UIColor yellowColor];
else
cell.backgroundView.backgroundColor = [UIColor blueColor];
return cell;
}
you can not use a view twice at the same time, which would occure when you have more than 3 cells. The reuising mechanism of the table should be sufficient enough.
I am not sure why u want to handle the backgroundViews seperatly from the cells.
Anyways, i altered your code so that there is no bug with missing backgroundViews:
NOTE! i did use ARC.
static NSString *identifierSingle = #"single";
static NSString *identifierTop = #"top";
static NSString *identifierBtm = #"btm";
static NSString *identifierMid = #"mid";
#implementation RootViewController {
NSMutableDictionary *_backgroundViewPool;
}
- (id)initWithStyle:(UITableViewStyle)style
{
if (self = [super initWithStyle:style]) {
_backgroundViewPool = [[NSMutableDictionary alloc] init];
UITableView *tableView = [self tableView];
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
}
return self;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 6;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0) {
return 1;
}
return 10;
}
- (NSString *)tableView:(UITableView *)tableView identifierForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSInteger maxRow = [tableView numberOfRowsInSection:section] - 1;
if (maxRow == 0) {
// single cell
return identifierSingle;
} else if (row == 0) {
// top cell
return identifierTop;
} else if (row == maxRow) {
// bottom cell
return identifierBtm;
} else {
// middle cell
return identifierMid;
}
}
- (UIColor *)tableView:(UITableView *)tableView colorForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSInteger maxRow = [tableView numberOfRowsInSection:section] - 1;
UIColor *color = nil;
if (maxRow == 0) {
// single cell
color = [UIColor blueColor];
} else if (row == 0) {
// top cell
color = [UIColor redColor];
} else if (row == maxRow) {
// bottom cell
color = [UIColor greenColor];
} else {
// middle cell
color = [UIColor yellowColor];
}
return color;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *colorIdentifier = [self tableView:tableView identifierForRowAtIndexPath:indexPath];
NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[[cell textLabel] setText:[NSString stringWithFormat:#"[%d, %d]", [indexPath section], [indexPath row]]];
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
NSMutableSet *set = [self backgroundPoolForIdentifier:colorIdentifier];
UIView *backgroundView = [set anyObject];;
if (backgroundView) {
[set removeObject:backgroundView];
} else {
backgroundView = [[UIView alloc] init];
[backgroundView setBackgroundColor:[self tableView:tableView colorForRowAtIndexPath:indexPath]];
}
[cell setBackgroundView:backgroundView];
return cell;
}
#pragma mark - Table view delegate
- (NSMutableSet *)backgroundPoolForIdentifier:(NSString *)identifier {
NSMutableSet *set = [_backgroundViewPool valueForKey:identifier];
if (!set) {
set = [[NSMutableSet alloc] init];
[_backgroundViewPool setValue:set forKey:identifier];
}
return set;
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[[self backgroundPoolForIdentifier:cell.reuseIdentifier] addObject:cell.backgroundView];
}
#end
Your original implementation didnt work because in cellForRowAtIndexPath: you sometimes returning a nil object. UITableView framework then passes that *cell object to willDisplayCell:(UITableViewCell*).
ie:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
....
return cell;
// cell maybe nil
If you do indeed perfer using your own caching mechanism, you can simply return a plain UITableViewCell object, dequeued if available or create a new one if none is available for reuse.
ie:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
return [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]
|| [UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
;
}
Then, there is the "view can only be added to 1 superview limit" causing your cached view to appear jumping.
Tried several things to do this but finally got satisfied on this very basic solutions, i know it's not really a charming one but it gave me smooth scrolling, you can try this if you like:
NSMutableArray *_viewArray;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
#define kTotalNoOfRows 1000
_viewArray = [[NSMutableArray alloc] initWithCapacity:kTotalNoOfRows];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
for (int i = 0; i < kTotalNoOfRows; i++) {
UIView * backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
if (kTotalNoOfRows == 0)
[backGroundView setBackgroundColor:[UIColor redColor]];
else if (i == 0)
[backGroundView setBackgroundColor:[UIColor greenColor]];
else if (i == (kTotalNoOfRows - 1))
[backGroundView setBackgroundColor:[UIColor blueColor]];
else
[backGroundView setBackgroundColor:[UIColor yellowColor]];
[_viewArray addObject:backGroundView];
}
return kTotalNoOfRows;
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = nil;
static NSString* middleCell = #"middleCell";
cell = [tableView dequeueReusableCellWithIdentifier:middleCell];
if(cell==nil) {
NSInteger maxRow = [tableView numberOfRowsInSection:indexPath.section] - 1;
if (maxRow != 0 && indexPath.row != 0 && indexPath.row != maxRow) {
middleCell = nil;
}
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:middleCell];
cell.backgroundView = [_viewArray objectAtIndex:indexPath.row];//assign your custom background view here
[cell.textLabel setBackgroundColor:[UIColor clearColor]];
}
cell.textLabel.text = [NSString stringWithFormat:#"%d",indexPath.row];
return cell;
}
Also I would like to mention my journey towards here; So what I have tried is
created a dictionary of Views:
UIView * _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIView * _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIView * _middleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIView * _lonelyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[_topView setBackgroundColor:[UIColor redColor]];
[_bottomView setBackgroundColor:[UIColor greenColor]];
[_middleView setBackgroundColor:[UIColor blueColor]];
[_lonelyView setBackgroundColor:[UIColor yellowColor]];
_viewDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
_topView, #"topView",
_bottomView, #"bottomView",
_middleView, #"middleView",
_lonelyView, #"lonelyView", nil];
returned copy of these view with unarchiver
- (UIView *) getBackgroundViewWith : (NSInteger) maxRow currentRow : (NSInteger) row{
if (maxRow == 0) {
return (UIView *)[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[_viewDictionary valueForKey:#"lonelyView"]]];//[[_viewDictionary valueForKey:#"lonelyView"] copy];
} else if (row == 0) {
return (UIView *)[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[_viewDictionary valueForKey:#"topView"]]];//[[_viewDictionary valueForKey:#"topView"] copy];
} else if (row == maxRow) {
return (UIView *)[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[_viewDictionary valueForKey:#"bottomView"]]];//[[_viewDictionary valueForKey:#"bottomView"] copy];
} else {
return (UIView *)[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[_viewDictionary valueForKey:#"middleView"]]];//[[_viewDictionary valueForKey:#"middleView"] copy];
}
return nil;
}
But it crash, while scrolling table with SIGBART. Thus gave up with this.
It's been a while since I've worked with tableviews, but I vaguely recall running into this problem. I believe the calls to the tableView:willDisplayCell:forRowAtIndexPath: method are threaded. When the user scrolls very fast multiple calls can get out simultaneously. In that case, given your current code, it is possible for multiple cells to get assigned the same view which will then cause the blank spaces.
If you use #synchronized(anObject){} to prevent multiple threads from running the same code simultaneously, you should be able to prevent the problem.
#synchronized (self) {
UIView *backgroundView = nil;
for (UIView *bg in _backgroundViewPool) {
if (color == [bg backgroundColor]) {
backgroundView = bg;
break;
}
}
if (backgroundView) {
[backgroundView retain];
[_backgroundViewPool removeObject:backgroundView];
} else {
backgroundView = [[UIView alloc] init];
[backgroundView setBackgroundColor:color];
}
}
According to my understanding of apple docs, when a cell is dequeued, it still has all it's views and settings you previously set.
Therefore, if you set a background view to cell it would still be there when it's dequeued and if it's a new cell it won't have background view.
I believe you don't need the background view pool since the OS handles that for you, so you can just reuse the BG view as you reuse the cell and do something like that in willDisplayCell: only
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSInteger maxRow = [tableView numberOfRowsInSection:section] - 1;
UIColor *color = nil;
if (maxRow == 0) {
// single cell
color = [UIColor blueColor];
} else if (row == 0) {
// top cell
color = [UIColor redColor];
} else if (row == maxRow) {
// bottom cell
color = [UIColor greenColor];
} else {
// middle cell
color = [UIColor yellowColor];
}
UIView *backgroundView = nil;
//***This is the different part***//
if (cell.backgroundView != nil) {
NSLog(#"Old Cell, reuse BG View");
backgroundView = cell.backgroundView;
} else {
NSLog(#"New Cell, Create New BG View");
backgroundView = [[UIView alloc] init];
[cell setBackgroundView:[backgroundView autorelease]];
}
[backgroundView setBackgroundColor:color];
}
Like that there is no need for the code didEndDisplayingCell: as well.

Resources