I have been playing around with this problem since a day and I have tried many ways to resolve this issue but have not yet succeeded. I have a tableview with 3 custom cells and I have added section header for last two sections. Here is the screen shot.
which shows last section header is repeating when I enter text in the TextView. My TextView is editable and I have disabled the scrolling to adjust the size of the textview as per the text size.
Here is the code.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *titleArray = #[#"",#"About You",#"Gender"];
NSString *titleHeading = [titleArray objectAtIndex:section];
return titleHeading;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return section == 0 ? CGFLOAT_MIN : 35;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = [NSString stringWithFormat:#"cell%ld,%ld",indexPath.section, indexPath.row];
id cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (indexPath.section == 1)
{
ProfileAboutCell *cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cellObj)
{
[_tableView registerNib:[UINib nibWithNibName:#"ProfileAboutCell" bundle:nil] forCellReuseIdentifier:identifier];
cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
}
cellObj.selectionStyle = UITableViewCellSelectionStyleNone;
//[cellObj.txtAboutYou layoutIfNeeded];
cellObj.txtAboutYou.delegate = self;
cellObj.lbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 0.0,cellObj.txtAboutYou.frame.size.width - 10.0, 34.0)];
cellObj.lbl.text = #"About You";
[cellObj.lbl setBackgroundColor:[UIColor clearColor]];
[cellObj.lbl setTextColor:[UIColor lightGrayColor]];
[cellObj.txtAboutYou addSubview:cellObj.lbl];
// [cellObj.txtAboutYou setText:[kUserDefaults valueForKey:kAbout]];
//[cellObj.txtAboutYou sizeToFit];
cell = cellObj;
}
return cell;
}
TextView Delegate Method.
-(void)textViewDidChange:(UITextView *)textView
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
ProfileAboutCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
if(![textView hasText]) {
cell.lbl.hidden = NO;
}
else{
cell.lbl.hidden = YES;
}
NSInteger len = textView.text.length;
cell.lblChar.text=[NSString stringWithFormat:#"%li",500-len];
[_tableView beginUpdates];
[_tableView endUpdates];
}
I have tried this #SO solution but no help. Any help would be much appreciated in this direction. Thanks in advance.
From my understanding of the issue you can solve it by set the sections headers in "titleForHeaderInSection" the same way you set the cells in "cellForRowAtIndexPath" for each section,
this way sections that you don't set Headers for will not cause any issue.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *titleArray = #[#"",#"About You",#"Gender"];
if (indexPath.section == 1) {
NSString *titleHeading = [titleArray objectAtIndex:1];
return titleHeading;
}
if (indexPath.section == 2) {
NSString *titleHeading = [titleArray objectAtIndex:2];
return titleHeading;
}
}
I am trying to keep the selected state of multiple cells on a didSelectRowAtIndexPath method. I have an edit button that I've set up that loops through every cell to select each field on my UITableView.
Here is the code for the edit button on tap that selects all my rows.
- (IBAction)editButtonTapped:(id)sender {
for (int i = 0; i < self.caseDataTableView.numberOfSections; i++) {
for (NSInteger r = 0; r < [self.caseDataTableView numberOfRowsInSection:i]; r++) {
[self tableView:caseDataTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:r inSection:i]];
}
}
}
When calling the didSelectRowAtIndexPath method, it does the following code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
OKOperatieNoteTableViewCell *cell = (OKOperatieNoteTableViewCell *)[self.caseDataTableView cellForRowAtIndexPath:indexPath];
cell.cellIndexPath = indexPath;
[cell hideLabelAndShowButtons];}
Incase you were wondering here is the hideLabelAndShowButtons method.
- (void)hideLabelAndShowButtons {
self.caseDataKeyLabel.hidden = NO;
if (!self.disabled) {
self.caseDataValueLabel.hidden = YES;
self.textField.hidden = NO;
if ([self.inputType isEqualToString:#"switcher"] || [self.inputType isEqualToString:#"multiselect"] || [self.inputType isEqualToString:#"picker"] || [self.inputType isEqualToString:#"DatePicker"] || [self.inputType isEqualToString:#"selectContact"]) {
self.button.hidden = NO;
}else {
self.button.hidden = YES;
}
}
self.caseDataDescriptionTextView.hidden = YES;}
Now at this point, I have all my rows selected. If I scroll down and then back up the selection of these rows is not there anymore. Now I'm aware when you go in and out of the view, the cellForRowAtIndexPath method recreates these cells. The following is my cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"caseData";
OKOperatieNoteTableViewCell * cell = [[OKOperatieNoteTableViewCell alloc]init];
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (indexPath.row < _procedureVariables.count) {
if ([[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] isEqualToString:#"Procedure"]) {
[cell setLabelsWithKey:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] AndValue:[self.model valueForKey:#"var_procedureName"]];
}else {
[cell setLabelsWithKey:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] AndValue:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"value"]];
}
OKProcedureTemplateVariablesModel *variableModel = _procedureVariables[indexPath.row];
cell.variable = variableModel.value;
[cell showLabelAndHideButtons];
cell.delegate = self;
[cell setUpCellType];
} else if (indexPath.row == _procedureVariables.count) {
NSString *text = [NSString stringWithFormat:#"%# \n\n %#", [_templateDictionary objectForKey:#"indicationText"], [_templateDictionary objectForKey:#"procedureText"] ];
[cell showDescription:text];
NSLog(#"cell.caseDataDescriptionTextView.font.fontName = %#", cell.caseDataDescriptionTextView.font.fontName);
}
cell.procedureID = _procedureID;
[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)];
return cell;
}
I'm just trying to figure out how to keep the selected state of these cells once the cellForRowAtIndexPath method is called. Any suggestions are welcomed.
i tried to simulate your situation, created a customCell and saved the indexpaths of selectedRows in my custom selectedPaths mutable array(initialized in viewDidLoad).
After every click i removed or added related indexpath to my array.
it worked for my case. Hope it helps.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"caseData";
NOTableViewCell *cell = (NOTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSLog(#"new cell created for row %d", (int)indexPath.row);
cell = [[[NSBundle mainBundle] loadNibNamed:#"NOTableViewCell" owner:self options:nil] objectAtIndex:0];
}
if ([selectedPaths indexOfObject:indexPath] != NSNotFound) // this cell is in selected state.
{
[cell.textLabel setText:#"This cell selected"];//selected state job.
return cell;
}
[cell.textLabel setText:[NSString stringWithFormat:#"%d", (int)indexPath.row]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([selectedPaths indexOfObject:indexPath] != NSNotFound) {
[selectedPaths removeObject:indexPath];
}
else{
[selectedPaths addObject:indexPath];
}
//[tableView reloadData];
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];//instead of reloading all just reload clicked cell.
}
You need to update the cell to selected and not selected explicitly in both directions in cellForRowAtIndexPath.
If not, the recycled cells will just show the value of the cell the cell was last used for until you change it.
While you are invoking the delegate method in order to call hideLabelAndShowButtons, you aren't telling the table view that you have selected the row;
- (IBAction)editButtonTapped:(id)sender {
for (int i = 0; i < self.caseDataTableView.numberOfSections; i++) {
for (NSInteger r = 0; r < [self.caseDataTableView numberOfRowsInSection:i]; r++) {
NSIndexPath *path=[NSIndexPath indexPathForRow:r inSection:i];
[caseDataTableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
[self tableView:caseDataTableView didSelectRowAtIndexPath:path];
}
}
}
Also, you aren't using the cell selection state in cellForRowAtIndexPath, so you probably need to change some code there too, but I am not sure what the relationship is between selected state and how you want to render the cell.
i am a developing a ios app with a view controller and a table view in it. i am trying to load list of items in 3 groups but when i compile it it shows correct count but not showing all the items jus repeating items. please help. let me post my code here.
#interface ViewController ()
#end
#implementation ViewController {
NSArray *menuItems;
NSArray *menuItems2;
NSArray *dash;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithWhite:0.6f alpha:1.0f];
self.tableView.backgroundColor = [UIColor colorWithWhite:0.6f alpha:1.0f];
self.tableView.separatorColor = [UIColor colorWithWhite:0.15f alpha:0.2f];
menuItems = #[#"itm1", #"itm2", #"itm3", #"itm4"];
menuItems2 = #[#"itm1", #"itm2", #"itm3", #"itm4"];
dash = #[#"itm1", #"itm2"];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0) {
return [menuItems count];
}
if (section == 1) {
return [menuItems2 count];
}
if (section == 2) {
return [dash count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
return cell;
}
#end
Your cellForRowAtIndexPath... method needs to be written so the cell is populated with proper data based on the cell's section and row. Right now you don't do anything but use an empty cell.
You don't configure your cells. After dequeuing a cell, you have to set its title.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Get the correct array, depending on the current section.
NSArray *items = nil;
if (indexPath.section == 0) {
items = menuItems;
}
else if (indexPath.section == 1) {
items = menuItems2;
}
else if (indexPath.section == 2) {
items = dash;
}
// Get the string from the array and set the cell's title
NSString *title = items[indexPath.row];
cell.textLabel.text = title;
return cell;
}
I've been trying to figuered this out for hours. I'm just plain old stuck here. What im trying to accomplish is basically inserting a row directly below the row just tapped in the tableview in addition i would like to add and image to the row and and make the image clickable to respond to its click event.
So here is my code.
I implemented (i belive) the nessesary methods to handle all the actions for the uitableview.
when the user taps the cell i handle that action by executing the following code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debug==1) {
NSLog(#"running line 225%# '%#'", self.class, NSStringFromSelector(_cmd));
}
Locations *location = nil;
Locations *tempObject = [[Locations alloc]init];
//test to see if we are looking for the search box or if we are essentially looking from the main view controller.
if (self.searchDisplayController.active) {
location= [self.searchResults objectAtIndex:indexPath.row];
NSLog(#"location : %#" ,location.locationName);
} else {
location = [self.locations objectAtIndex:indexPath.row];
NSLog(#"location : %#" ,location.locationName);
//set the new indexpath to 1 more then before so that we can essetially add a row right below the actual tapped item.
NSIndexPath *newPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
indexPath = newPath;
[self.locations insertObject:tempObject atIndex:indexPath.row ];
[tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
self.visibleCell =YES; //set this boolean variable so that we can add a specific row image to this var
// self.locations[0].isItVisible = YES;
}//ends the else statement.
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
the above code inserts an empty cell into my tableview.
however how can i set the cell so that its custom and not the same as the others. In other words my initial cells data-source are basically bound to an nsobject and a string property location-name. However when i go try to update the table cells in the above method i obviously cannot add an image into a string so I'm running in to a error.
so i tried to instead make the update on the
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
by basically checking if a variable is set to true or false but that turned out to be buggy because even when i scroll this method gets called.
How should i go about doing this. I think i have to do it all in the didselectrowindexaspath method. But i cant figured out how to change the newly inserted cell to contain an image only.
Any help would be appreciated.
EDIT
here is what im doing to try to add the image under the cellforrowindexpath method.
if(self.visibleCell==YES){
UIImage *clkImg = [UIImage imageNamed:#"alarm_clock.png"];
cell.imageView.image = clkImg;
}
Im a noob so im not sure im doing this correctly.
EDIT
this is the full cellforatindexpath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debug==1) {
NSLog(#"running line 159 %# '%#'", self.class, NSStringFromSelector(_cmd));
}
// NSLog(#"cell for row at index path just got called");
//JAMcustomCell *myCell = [[JAMcustomCell alloc]init];
static NSString *CellIdentifier = #"ListPrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Locations * locations = [[Locations alloc]init];
//tableView.backgroundColor = [UIColor blackColor];
// NSLog(#"this is visible '%hhd'", locations.isItVisible);
if(self.visibleCell==YES){
UIImage *clkImg = [UIImage imageNamed:#"alarm_clock.png"];
cell.imageView.image = clkImg;
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
locations = [self.searchResults objectAtIndex:indexPath.row];
}
else{
locations = [self.locations objectAtIndex:indexPath.row];
}
cell.textLabel.text = locations.locationName;
cell.textLabel.textColor = [UIColor whiteColor];
//cell.backgroundColor =[UIColor blackColor];
// cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"Graytbl.fw.png"]];
cell.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"blueTbl.fw.png"]];
cell.selectedBackgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"blueTbl.fw.png"]];
// UIFont *myFont = [ UIFont fontWithName: #"Oswald" size: 25.0 ];
// cell.textLabel.font = myFont;
cell.textLabel.font= self.MyFont;//[UIFont fontWithName:#"Oswald-Regular.ttf" size:15];
return cell;
}
Try this approach, I used your idea of Bool
#pragma mark - Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.visibleCell){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"imageViewCell" forIndexPath:indexPath];//ListPrototypeCell
UIImageView *imageVIew = (UIImageView *)[cell viewWithTag:1];
[imageVIew setImage:[UIImage imageNamed:#"alarm_clock.png"]];
return cell;
}else{
return [tableView dequeueReusableCellWithIdentifier:#"ListPrototypeCell" forIndexPath:indexPath];
}
}
#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(!self.visibleCell){
self.numberOfRows++;
self.visibleCell = YES;
NSIndexPath *indexPathCell = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPathCell] withRowAnimation:UITableViewRowAnimationBottom];
}else{
self.numberOfRows--;
self.visibleCell = NO;
NSIndexPath *indexPathCell = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.tableView deleteRowsAtIndexPaths:#[indexPathCell] withRowAnimation:UITableViewRowAnimationTop];
}
}
I created a demo project for you.
I hope it helps
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.