I'm trying to create a UITableview, where each cell contains another UITableView. It's basically a list of 2-3 rows, where each row then has a sublist of 2-3 rows inside.
The main ViewController behaves just like any other TableViewController, and inside the cellForRowAtIndexPath, it attempts to add a SubTableViewController.view with a dynamic height. The SubTableViewController is the second tableview and each has their own Datasource.
The problem I'm running into is the SubTableViewController appears to render properly using the debugger, with the correct data and number of cells, but it simply isn't appearing when rendering. I noticed it has a contentSize height of "0" in its ViewDidAppear, despite having 2+ rows produced with height. The project uses AutoLayout but the SubTableViewController's frame is set programmatically when added.
Any ideas what I can do to get something to appear here?
Structure of Data (periods are the subTable)
[{name:"activity 1",
periods:[{name:"period1",desc:"desc1"},
{name:"period2",desc:"desc2"},
{name:"period3",desc:"desc3"}
]
},
{name:"activity 2",
periods:[{name:"period1",desc:"desc1"},
{name:"period2",desc:"desc2"},
{name:"period3",desc:"desc3"}
]
}]
ViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_data count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
UIImageView *imageView = (UIImageView*)[cell viewWithTag:1];
UIView *subTableView = (UIView*)[cell viewWithTag:3];
return imageView.frame.size.height + subTableView.frame.size.height + 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"tableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
ActivityModel *model = _data[indexPath.row];
UILabel *nameLabel = (UILabel*)[cell viewWithTag:2];
nameLabel.text = model.name;
UIView *internalView = (UIView*)[cell viewWithTag:10];
SubTableViewController *subTableViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"SubTableViewController"];
subTableViewController.activityModel = model;
subTableViewController.view.tag = 3;
subTableViewController.view.frame = CGRectMake(0,
60,
internalView.frame.size.width,
subTableViewController.view.frame.size.height);
[internalView addSubview:subTableViewController.view];
[internalView bringSubviewToFront:subTableViewController.view];
[subTableViewController.tableView reloadData];
return cell;
}
SubTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
int height = 0;
for (int section = 0; section < [self numberOfSectionsInTableView:_tableView]; section++){
for(int row = 0; row < [self tableView:_tableView numberOfRowsInSection:section]; row++){
height += [self tableView:_tableView heightForRowAtIndexPath:[NSIndexPath indexPathForItem:row inSection:section]];
}
}
CGRect tableFrame = self.tableView.frame;
tableFrame.size.height = height;
self.tableView.frame = tableFrame;
CGRect viewFrame = self.view.frame;
viewFrame.size.height = height;
self.view.frame = viewFrame;
[self.view bringSubviewToFront:_tableView];
// [self.tableView layoutIfNeeded];
// [self.tableView setNeedsDisplay];
// [self.tableView reloadData];
// _tableView.contentSize = CGSizeMake(600, 52);
self.view.backgroundColor = [UIColor redColor];
self.tableView.backgroundColor = [UIColor blueColor];
self.tableView.hidden = NO;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_activityModel.periods count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
UILabel *nameLabel = (UILabel*)[cell viewWithTag:3];
UITextView *textView = (UITextView*)[cell viewWithTag:5];
float textViewHeight = [textView.text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 40, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
return nameLabel.frame.size.height + textViewHeight + 20;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"tableViewCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
PeriodModel *model = _activityModel.periods[indexPath.row];
UILabel *nameLabel = (UILabel*)[cell viewWithTag:3];
UILabel *durationLabel = (UILabel*)[cell viewWithTag:4];
UITextView *textView = (UITextView*)[cell viewWithTag:5];
nameLabel.text = model.name;
durationLabel.text = [NSString stringWithFormat:#"%d minutes", (int)(model.durationSeconds/60)];
textView.text = model.description;
textView.textContainerInset = UIEdgeInsetsZero;
textView.textContainer.lineFragmentPadding = 0;
textView.scrollEnabled = NO;
CGRect frame = textView.frame;
frame.size.height = [textView.text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(cell.contentView.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
textView.frame = frame;
return cell;
}
Simulator Image. The title is the outer UITableCell, and below it in red is the added SubTableViewController.view. The UITableView should cover the red, but is not appearing at all here. It is not hidden, underneath, etc.
Do not put a table view inside your cells.
There is little benefit to doing this for your described use. Use sections and rows. Each section would be your current cell. And each row in that section would be a row from your current embedded table view.
Further, if your internal table views had differing sizes you would be needing to calculate all of the internal cell heights for each external cell. That is exactly what happens with sections and rows, but you as the developer only need to worry about the rows and UITableView will handle the section sizing.
I've added a UIScrollView in each UITableViewCell of a UITableView.
This is my code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* CellIdentifier = #"Cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIScrollView *propertyScrollView;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
propertyScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, tableView.frameWidth, 100)];
[propertyScrollView setContentSize:CGSizeMake(10*tableView.frameWidth, 100)];
[propertyScrollView setPagingEnabled:YES];
propertyScrollView.delegate = self;
propertyScrollView.tag = indexPath.row;
[[cell contentView] addSubview:propertyScrollView];
propertyScrollView.backgroundColor = [UIColor blackColor];
int pagingIndex = [[m_pagingIndexArray objectAtIndex:indexPath.row]intValue];
[propertyScrollView setContentOffset:CGPointMake(pagingIndex*propertyScrollView.frameWidth, 0)];
for(int i=0;i<10;i++)
{
UIButton *singleImage = [[UIButton alloc]initWithFrame:CGRectMake(i*tableView.frameWidth, 0, propertyScrollView.frameWidth, propertyScrollView.frameHeight)];
[propertyScrollView addSubview:singleImage];
singleImage.titleLabel.text = [NSString stringWithFormat:#"%d",i];
singleImage.titleLabel.textColor = [UIColor blackColor];
singleImage.titleLabel.font = systemFontBoldTypeOfSize(20);
[singleImage setImage:[horizentalImagesArray objectAtIndex:i] forState:UIControlStateNormal];
singleImage.backgroundColor = [UIColor whiteColor];
}
else
{
propertyScrollView.tag = indexPath.row;
int pagingIndex = [[m_pagingIndexArray objectAtIndex:indexPath.row]intValue];
[propertyScrollView setContentOffset:CGPointMake(pagingIndex*propertyScrollView.frameWidth, 0)];
}
return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int pageIndex = scrollView.contentOffset.x/scrollView.frameWidth;
[m_pagingIndexArray replaceObjectAtIndex:scrollView.tag withObject:[NSString stringWithFormat:#"%d",pageIndex]];
}
- (void)viewDidLoad {
[super viewDidLoad];
m_pagingIndexArray = [[NSMutableArray alloc]init];
for(int i=0;i<10;i++)
{
[m_pagingIndexArray addObject:#"0"];
}
}
I'm adding 10 UIButtons in a single UIScrollView(Paging Enabled).
The problem is, if I scroll any one of the UITableViewCell's scrollview and move to bottom cells, I can see some other UITableViewCell's scrollviews also scrolled to that content offset point.
I want all my UITableview cell's UIScrollView to scroll independently. How can I achieve it? Please help me to sort out this issue.
You are keeping the current page number in m_pagingIndexArray, and the same array is used for all the cells, so suppose if it contains the page number as 3, then it will be applicable for all the cells.
Also you need to reset the text and image of each button for each cell if it's being reused as I have added below-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = nil;
UIScrollView *propertyScrollView;
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
propertyScrollView = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, tableView.frameWidth, 100)] autorelease];
[propertyScrollView setContentSize:CGSizeMake(10*tableView.frameWidth, 100)];
[propertyScrollView setPagingEnabled:YES];
propertyScrollView.delegate = self;
propertyScrollView.tag = indexPath.row;
[[cell contentView] addSubview:propertyScrollView];
propertyScrollView.backgroundColor = [UIColor blackColor];
int pagingIndex = [[m_pagingIndexArray objectAtIndex:indexPath.row]intValue];
[propertyScrollView setContentOffset:CGPointMake(pagingIndex*propertyScrollView.frameWidth, 0)];
for(int i=0;i<10;i++)
{
UIButton *singleImage = [[[UIButton alloc]initWithFrame:CGRectMake(i*tableView.frameWidth, 0, propertyScrollView.frameWidth, propertyScrollView.frameHeight)] autorelease];
[propertyScrollView addSubview:singleImage];
singleImage.titleLabel.text = [NSString stringWithFormat:#"%d",i];
singleImage.titleLabel.textColor = [UIColor blackColor];
singleImage.titleLabel.font = systemFontBoldTypeOfSize(20);
[singleImage setImage:[horizentalImagesArray objectAtIndex:i] forState:UIControlStateNormal];
singleImage.backgroundColor = [UIColor whiteColor];
}
return cell;
}
Your code is correct for the case if cell is not reused, but as the cells are reused you need to set the content offset for scroll view of each cell if they are reused.
You need to write an else case -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(cell == nil)
{
// your code
}
else
{
// reset the content offset of the scroll view as per your needs for the reused cells
}
return cell;
}
Hi I want to display images in UITableview and on top of uitableview I need transparent view.
What I have tried is :
Added view in storyboard and on top of it UITableView.
_vaultView.backgroundColor = [UIColor colorWithRed:26/255.0f green:188/255.0f blue:156/255.0f alpha:0.85f];
Ian unable to display transparent View.
Please suggest me how to proceed further.
edit:
- (void)viewDidLoad {
[super viewDidLoad];
_vaultView.backgroundColor = [UIColor colorWithRed:26/255.0f green:188/255.0f blue:156/255.0f alpha:0.85f];
UILabel *lblMySaved = [self createLabelWithTitle:#"Find all your saved work here" frame:CGRectMake(20,115,300,60) tag:1 font:[Util Font:FontTypeLight Size:18.0] color:[UIColor whiteColor] numberOfLines:0];
[_vaultView addSubview:lblMySaved];
_tblVault.separatorColor = [UIColor clearColor];
_tblVault.delegate = self;
_tblVault.dataSource = self;
_tblVault.scrollEnabled = NO;
[self refreshImages];
}
-(void)refreshImages
{
[aryVaultImages removeAllObjects];
NSArray *aryImages = [self getImagesfromDB]; // Retrieving image paths from DB
[_tblVault reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
tableView.separatorColor =[UIColor clearColor];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
if(indexPath.row ==0 && [aryImgPaths count])
{
NSLog(#"imagepath:%#",[aryImgPaths objectAtIndex:indexPath.row]);
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5,5, 40, 40)];
[imageView setImage:[UIImage imageNamed:#"deletePost11.png"]];
[cell.contentView sendSubviewToBack:imageView];
[cell.contentView addSubview:imageView];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
From my understanding of your Views stack in your viewController, you simply need to move the transparent view to the front of the stack (it is currently at the back of your superView).
You can do this by calling.
[self.view bringSubViewToFront:<your transparent view>];
And in the storyboard just set the view to the correct values
If you want to hide the view just call
[self.view bringSubViewToFront:<your tableView>];
EDIT
To create a transparent view on top of you UITableView, you need to add a UIView in the storyBoard that is a subView of your viewController main view(then set all the attributes you want in the attributes inspector). Your tableView need to be also a subView of your viewController main view.
*make sure that the transparent view is front of the tableView in your storyBoard
In order to handle the gestures (because the transparent view is "blocking" the gestures from the tableView read this post Link)
tableView.backgroundColor = [UIColor clearColor];
tableView.backgroundView.backgroundColor = [UIColor clearColor];
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
if ([view isKindOfClass:[UITableViewHeaderFooterView class]])
{
UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
headerView.contentView.backgroundColor = [UIColor clearColor];
headerView.backgroundView.backgroundColor = [UIColor clearColor];
}
}
In my iOS app, I want to fresh the entire contents of a tableView when the viewController is loaded. Each cell of a tableView has a textLabel that is the name of a step object.
I've ensured that when I return to the viewController, the correct stepNames are loaded (I know this by logging the names of the steps). However, the name of the step is not updated in the tableView.
How can I ensure that the labels of the tableView cells are loading properly?
How I try to trigger a refresh of the TableView:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
if(reloadSteps == YES){
NSLog(#"reloading steps");
NSData * stepsData = [NSData dataWithContentsOfURL:stepsURL];
[self fetchProjectSteps:stepsData];
[self.projectInfo reloadData];
int numRows = [stepNames count];
NSLog(#"numRows %i", numRows);
for(int i =0; i<numRows; i++){
[self tableView:self.projectInfo cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
}
}
}
How each cell of the tableView is rendered:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"in cellForRowAtIndexPath");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"StepCell"];
}
if (indexPath.row ==0) {
cell.textLabel.font = [UIFont systemFontOfSize:16];
cell.textLabel.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
cell.textLabel.text = #"Project Description";
cell.textAlignment = NSTextAlignmentCenter;
} else {
cell.userInteractionEnabled = YES;
cell.textLabel.font = [UIFont systemFontOfSize:16.0];
cell.textLabel.text = [stepNames objectAtIndex:indexPath.row];
NSLog(#"textLabel: %#", cell.textLabel.text); // THIS IS CORRECT, BUT DOES NOT APPEAR TO BE UPDATED IN THE TABLEVIEW
if(![[stepImages objectAtIndex:indexPath.row] isEqual: #""]) {
cell.accessoryView = [stepImages objectAtIndex:indexPath.row];
}
}
return cell;
}
Here is my header file:
#interface EditProjectViewController : UIViewController <UIActionSheetDelegate, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>{
#property (strong,nonatomic) IBOutlet UITableView *projectInfo;
}
and then in my implementation file:
-(void) viewDidLoad{
self.projectInfo = [[UITableView alloc]init];
self.projectInfo.delegate = self;
}
Delete all this:
int numRows = [stepNames count];
NSLog(#"numRows %i", numRows);
for(int i =0; i<numRows; i++){
[self tableView:self.projectInfo cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
}
Your reloadData call will call cellForRowAtIndexPath: for every cell in your table view. Just make sure you're returning stepNames.count for numberOfRowsInSection:.
EDIT
I've looked over your updated code. A couple things (including what your problem most likely is):
Your projectInfo outlet should be weak, not strong (since it's an IBOutlet)
Even though you have your table view linked up in the interface file, you're initializing it in viewDidLoad, creating a new instance
Change the following:
-(void) viewDidLoad{
self.projectInfo = [[UITableView alloc]init];
self.projectInfo.delegate = self;
}
To this:
-(void) viewDidLoad{
self.projectInfo.dataSource = self;
self.projectInfo.delegate = self;
}
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.