UITableViewCell with alternate background color in customized cells - objective-c

I'd like the background to of my UITableViewCells to have a different color every two cells displayed, but when I scroll down and back, they all get the same color. How can I get this effect knowing that my cells have different contentView size (according to their content) ?
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 20.0f
#define NAME_CELL_HEIGHT 20.0f
#import "CartCell.h"
#implementation CartCell
#synthesize nameLabel = _nameLabel;
#synthesize ingredientsLabel = _ingredientsLabel;
#synthesize myStore;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
myStore = [Store sharedStore];
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.nameLabel = nil;
self.ingredientsLabel = nil;
// SET "NAME" CELL
self.nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[self.nameLabel setLineBreakMode:UILineBreakModeWordWrap];
[self.nameLabel setMinimumFontSize:FONT_SIZE];
[self.nameLabel setNumberOfLines:1];
[self.nameLabel setTag:1];
self.nameLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18];
[self.nameLabel sizeToFit];
self.nameLabel.backgroundColor = [UIColor clearColor];
[[self contentView] addSubview:self.nameLabel];
// SET "INGREDIENTS" CELL
self.ingredientsLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[self.ingredientsLabel setLineBreakMode:UILineBreakModeWordWrap];
[self.ingredientsLabel setMinimumFontSize:FONT_SIZE];
[self.ingredientsLabel setNumberOfLines:0];
[self.ingredientsLabel setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[self.ingredientsLabel setTag:2];
self.ingredientsLabel.backgroundColor = [UIColor clearColor];
[[self contentView] addSubview:self.ingredientsLabel];
if (myStore.cellBackgroundShouldBeLight == YES) {
NSLog(#"clear [in] ? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
self.contentView.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = NO;
} else {
NSLog(#"clear [in] ? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
self.contentView.backgroundColor = [[UIColor alloc]initWithRed:187.0/255.0 green:268.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = YES;
}
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
UPDATE:
I'm know trying to set it in cellForRowAtIndexPath as it was suggested, but I get the same result: scrolling down worked fine the first time, but then scrolling up again messed up the cells background color.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CartCell";
CartCell *cell = (CartCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Recipes *info = [_fetchedResultsController objectAtIndexPath:indexPath];
if (cell == nil)
{
cell = [[CartCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// if (!cell.nameLabel) {
// cell.nameLabel = (UILabel*)[cell viewWithTag:1];
// // cell.nameLabel = (UILabel*)[cell viewWithTag:1];
// }
// if (!cell.ingredientsLabel)
// cell.ingredientsLabel = (UILabel*)[cell viewWithTag:2];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [info.ingredients sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[cell.nameLabel setFrame:CGRectMake(10, 10, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), NAME_CELL_HEIGHT)];
[cell.ingredientsLabel setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN + NAME_CELL_HEIGHT, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
// SETTING TEXT CONTENT
cell.nameLabel.text = info.name;
cell.ingredientsLabel.text = info.ingredients;
// SETTING BACKGROUND COLOR
// UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
// [lab setBackgroundColor:[UIColor blueColor]];
if (myStore.cellBackgroundShouldBeLight == YES) {
NSLog(#"clear? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:84.0/255.0 blue:229.0/255.0 alpha:1];
// cell.backgroundView = lab;
// ingredientsLabel.backgroundColor = [UIColor clearColor];
// nameLabel.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1];
// [cell setBackgroundColor: [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1]];
// [cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:1]];
myStore.cellBackgroundShouldBeLight = NO;
} else {
// cell.contentView.tag = 2;
NSLog(#"clear? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:187.0/255.0 green:184.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = YES;
}
return cell;
}

It is very simple, the indexPath tells you everything you need to know. If the indexPath.row is even then use one color. If the indexPath.row is odd use a different color.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
…
// SETTING BACKGROUND COLOR
// UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
// [lab setBackgroundColor:[UIColor blueColor]];
if (indexPath.row % 2) {
cell.contentView.backgroundColor = [[[UIColor alloc]initWithRed:87.0/255.0 green:84.0/255.0 blue:229.0/255.0 alpha:1] autorelease];
} else {
cell.contentView.backgroundColor = [[[UIColor alloc]initWithRed:187.0/255.0 green:184.0/255.0 blue:229.0/255.0 alpha:1] autorelease];
}
…
return cell;
}
Your method is having problems because blindly assuming cells will be asked for in alternating pairs is a bad assumption. The tableView could ask for cells in any order is chooses. In your example, I believe cells could be asked for as follows. First, 0, 1,…, 9 are asked for. Next, you scroll down and 10, 11, and 12 are fetched. At this point, 0, 1, and 2 have gone off the screen. You scroll back up and 2 is asked for, but oh no, your model is on an odd number alternation, so you get the wrong color.

Use the -willDisplayCell method.
- (void)tableView: (UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath: (NSIndexPath *)indexPath {
if (indexPath.row %2) { //change the "%2" depending on how many cells you want alternating.
UIColor *altCellColor = [UIColor colorWithRed:255/255.0 green:237/255.0 blue:227/255.0 alpha:1.0]; //this can be changed, at the moment it sets the background color to red.
cell.backgroundColor = altCellColor;
}
else if (indexPath.row %2) {
UIColor *altCellColor2 = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.0]; //this can be changed, at the moment it sets the background color to white.
cell.backgroundColor = altCellColor2;
}
}

The appropriate place to change your cell's background color would be the "cellForRowAtIndexPath:" method, where the cells data gets filled out and returned to the table view.
One way to do this would be: When the data goes into the cell, change the background color depending on what row you're on.

Put the color on the cellForRowAtIndexPath: don't set on custom cell.

Take a look what I use to customize my table
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#if USE_CUSTOM_DRAWING
const NSInteger TOP_LABEL_TAG = 1001;
const NSInteger BOTTOM_LABEL_TAG = 1002;
UILabel *topLabel;
UILabel *bottomLabel;
#endif
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//
// Create the cell.
//
cell =
[[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
autorelease];
#if USE_CUSTOM_DRAWING
UIImage *indicatorImage = [UIImage imageNamed:#"indicator.png"];
cell.accessoryView =
[[[UIImageView alloc]
initWithImage:indicatorImage]
autorelease];
const CGFloat LABEL_HEIGHT = 20;
UIImage *image = [UIImage imageNamed:#"imageA.png"];
//
// Create the label for the top row of text
//
topLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT),
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:topLabel];
//
// Configure the properties for the text that are the same on every row
//
topLabel.tag = TOP_LABEL_TAG;
topLabel.backgroundColor = [UIColor clearColor];
topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
//
// Create the label for the top row of text
//
bottomLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT) + LABEL_HEIGHT,
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:bottomLabel];
//
// Configure the properties for the text that are the same on every row
//
bottomLabel.tag = BOTTOM_LABEL_TAG;
bottomLabel.backgroundColor = [UIColor clearColor];
bottomLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
bottomLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
bottomLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
//
// Create a background image view.
//
cell.backgroundView =
[[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView =
[[[UIImageView alloc] init] autorelease];
#endif
}
#if USE_CUSTOM_DRAWING
else
{
for (UIView *sub in [cell.contentView subviews]) {
// if([sub class] == [UITableViewCellContentView class])
NSLog(#"this is uilabel %#",[sub class]);
}
topLabel = (UILabel *)[cell viewWithTag:TOP_LABEL_TAG];
bottomLabel = (UILabel *)[cell viewWithTag:BOTTOM_LABEL_TAG];
}
topLabel.text = [NSString stringWithFormat:#"Cell at row %ld.", [indexPath row]];
bottomLabel.text = [NSString stringWithFormat:#"Some other information.", [indexPath row]];
//
// Set the background and selected background images for the text.
// Since we will round the corners at the top and bottom of sections, we
// need to conditionally choose the images based on the row index and the
// number of rows in the section.
//
UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
rowBackground = [UIImage imageNamed:#"topRow.png"];
selectionBackground = [UIImage imageNamed:#"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"bottomRow.png"];
selectionBackground = [UIImage imageNamed:#"bottomRowSelected.png"];
}
else
{
rowBackground = [UIImage imageNamed:#"middleRow.png"];
selectionBackground = [UIImage imageNamed:#"middleRowSelected.png"];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
// cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:rowBackground];
// cell.selectedBackgroundView.backgroundColor = [UIColor colorWithPatternImage:selectionBackground];
//
// Here I set an image based on the row. This is just to have something
// colorful to show on each row.
//
if ((row % 3) == 0)
{
cell.imageView.image = [UIImage imageNamed:#"imageA.png"];
}
else if ((row % 3) == 1)
{
cell.imageView.image = [UIImage imageNamed:#"imageB.png"];
}
else
{
cell.imageView.image = [UIImage imageNamed:#"imageC.png"];
}
#else
cell.text = [NSString stringWithFormat:#"Cell at row %ld.", [indexPath row]];
#endif
return cell;
}
past it after all #import lines
#define USE_CUSTOM_DRAWING 1

Heading ##Simplest way of changing alternate colors
if(indexPath.row%2) {
cell.backgroundColor=[UIColor nameUrColor] //brownColor, yellowColor, blueColor
} else {
cell.backgroundColor=[UIColor nameAnotherColor]
}

if(cell.contentView)
{
[cell.nameLbl setFont:[UIFont systemFontOfSize:24]];
int red_value = arc4random() % 210;
int green_value = arc4random() % 210;
int blue_value = arc4random() % 210;
cell.contentView.backgroundColor = [UIColor colorWithRed:red_value/255.0 green:green_value/255.0 blue:blue_value/255.0 alpha:0.6];
}

Related

UIImageView transparent black on a cell bug (Objective-C)

I have a UIImageView installed on my cell, it is transparent black, but when I scroll the CollectionView and I raise my UIImageView but there is always more to transprence.
See picture :
1 - I is not even scroll
2 - After a scroll
My code :
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"pictureCell";
MSContestListCollectionViewCell *cell = (MSContestListCollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.titleContest.adjustsFontSizeToFitWidth = YES;
cell.titleContest.minimumScaleFactor = 0.5;
cell.pictureImageView.layer.cornerRadius = 5;
cell.pictureImageView.clipsToBounds = YES;
cell.titleView.layer.cornerRadius = 5;
cell.titleView.clipsToBounds = YES;
switch (_segmentedControl.selectedSegmentIndex) {
case 0: {
NSDictionary *searchResult = [self.readArray objectAtIndex:indexPath.item];
NSString *stringImage = [searchResult objectForKey:#"featuredImage"];
NSString *image = [NSString stringWithFormat:#"https://srv.mediaswapp.com/%#", stringImage];
[cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.statusContest.text = [searchResult objectForKey:#"status"];
if ([[searchResult objectForKey:#"status"] isEqualToString:#"PAUSE"]) {
cell.titleContest.text = [NSString stringWithFormat:#"Concours en pause"];
/*
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, cell.contentView.frame.size.height)];
view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8f];
view.layer.cornerRadius = 5;
view.clipsToBounds = YES;
[cell.contentView addSubview:view];
*/
UIImageView *imagecellPause = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, cell.contentView.frame.size.height)];
UIImage *cellImage = [UIImage imageNamed:#"cell-pause.png"];
imagecellPause.image = cellImage;
[cell.contentView addSubview:imagecellPause];
UIImageView *imagePause = [[UIImageView alloc] initWithFrame:CGRectMake(69.5, 69.5, 25, 25)];
UIImage *image = [UIImage imageNamed:#"Pause Filled-50 (1).png"];
imagePause.image = image;
[cell.contentView addSubview:imagePause];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 90, 150, 50)];
label.textColor = [UIColor whiteColor];
label.font = [UIFont fontWithName:#"Avenir-Book" size:12];
label.text = [searchResult objectForKey:#"description"];
label.adjustsFontSizeToFitWidth = YES;
label.minimumScaleFactor = 0.5;
[cell.contentView addSubview:label];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 105, 150, 50)];
label2.textColor = [UIColor whiteColor];
label2.font = [UIFont fontWithName:#"Avenir-Black" size:15];
label2.text = #"Concours en pause";
[cell.contentView addSubview:label2];
cell.titleView.hidden = YES;
} else {
cell.titleContest.text = [searchResult objectForKey:#"description"];
}
break;
}
case 1: {
NSDictionary *searchResult2 = [self.readArrayWinner objectAtIndex:indexPath.item];
NSString *stringImage = [searchResult2 objectForKey:#"featuredImage"];
NSString *image = [NSString stringWithFormat:#"https://srv.mediaswapp.com/%#", stringImage];
[cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.titleContest.text = [searchResult2 objectForKey:#"description"];
cell.statusContest.text = [searchResult2 objectForKey:#"status"];
NSLog(#"le gagnant : %#", [searchResult2 valueForKeyPath:#"winners.name"]);
break;
}
case 2: {
NSDictionary *searchResult3 = [self.readArrayPhotos objectAtIndex:indexPath.item];
NSString *stringImage = [searchResult3 objectForKey:#"featuredImage"];
NSString *image = [NSString stringWithFormat:#"https://srv.mediaswapp.com/%#", stringImage];
[cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.titleContest.text = [searchResult3 objectForKey:#"description"];
cell.statusContest.text = [searchResult3 objectForKey:#"status"];
break;
}
default:
break;
}
[_activity stopAnimating];
_label1.hidden = YES;
return cell;
}
Your CellForRowAtIndexPath should never contain addSubView, since everytime the cell is reloaded it will add the view. Thats why it keeps getting darker, it just adds view onto view.
Instead you should subclass your UICollectionViewCell and add the view in the subclass.

UITableView multiple sections with GUI Elements UIButton, UISwitch, etc

I have been racking my brain on this problem for a day or so now... I've searched this forum as well as google and other blogs etc. All to no avail.
What i'm doing is creating a UITableView with multiple sections and within each section, each row has a different GUI element (i.e. a settings screen)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
and all I'm looking to achieve is that each section to have various GUI elements in various cells. BUT as you can see in this screenshot:
Initially everything appears as it should, but after scrolling UP and DOWN once, the problems begin. Elements begin to shuffle around and the more/longer you scroll UP and DOWN the more the elements move around.
!["UITableView with GUI elements in sections and rows. Bug? Glitch? Ignorance?"][2]
Is this a bug? glitch? or ignorance? (probably the latter) - I've stripped out all other code except for the GUI code and if it means anything I'm creating the UITableView using a NIB
Also, here's the code for my cellForRowAtIndexPath method. I will be eternally grateful if someone could point me in the right direction or tell me what i'm doing wrong.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell
// desired section
if(indexPath.section == 0) {
//
// Load Settings
//
// button
UIButton * loadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
loadButton.frame = CGRectMake(0.0, 0.0, 300.0, 44.0);
[loadButton setTitle:#"Load Image" forState:UIControlStateNormal];
[loadButton setTitle:#"Load Image" forState:UIControlStateSelected];
[loadButton addTarget:self action:#selector(loadImage:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:loadButton];
} else if(indexPath.section == 1) {
//
// Mode Settings
//
if(indexPath.row == 0) {
cell.text = [mode objectAtIndex:indexPath.row];
} else if(indexPath.row == 1) {
cell.text = [mode objectAtIndex:indexPath.row];
}
} else if(indexPath.section == 2) {
//
// Marker Settings
//
if(indexPath.row == 0) {
// description text
cell.text = [marker objectAtIndex:indexPath.row];
// switch
UISwitch *markerSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = markerSwitch;
[markerSwitch setOn:YES animated:NO];
[markerSwitch addTarget:self action:#selector(markerToggle:) forControlEvents:UIControlEventValueChanged];
[markerSwitch release];
} else if(indexPath.row == 1) {
UISlider *markerGridSlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0, 10.0, 284, 10.0)];
cell.accessoryView = markerGridSlider;
markerGridSlider.minimumValueImage = [UIImage imageNamed:#"size_icon_1x1.png"];
markerGridSlider.maximumValueImage = [UIImage imageNamed:#"size_icon_8x8.png"];
[markerGridSlider setMinimumValue:1.0];
[markerGridSlider setMaximumValue:8.0];
markerGridSlider.value = 8.0;
[markerGridSlider addTarget:self action:#selector(markerGrid:) forControlEvents:UIControlEventValueChanged];
[markerGridSlider release];
} else if(indexPath.row == 2) {
UISlider *markerSpacingSlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0, 10.0, 284, 10.0)];
cell.accessoryView = markerSpacingSlider;
markerSpacingSlider.minimumValueImage = [UIImage imageNamed:#"spacing_icon_min.png"];
markerSpacingSlider.maximumValueImage = [UIImage imageNamed:#"spacing_icon_max.png"];
[markerSpacingSlider setMinimumValue:1.0];
[markerSpacingSlider setMaximumValue:(320.0/8.0)];
markerSpacingSlider.value = 1.0;
[markerSpacingSlider addTarget:self action:#selector(markerSpacing:) forControlEvents:UIControlEventValueChanged];
[markerSpacingSlider release];
}
}
return cell;
}
thanks.
Ken
thanks alon for the help.
maybe i'm not understanding exactly what you mean, but i think i've implemented your suggestions properply. however i still get the glitch of the elements swapping places although now after about 5+ UP and DOWN swipes and my UISwitch is now placed in the top left corner.
here's my updated code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if([indexPath section] == 0) {
//
// Load Settings
//
// button
UIButton *loadButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] autorelease];
loadButton.frame = CGRectMake(0.0, 0.0, 300.0, 44.0);
[loadButton addTarget:self action:#selector(loadImage:) forControlEvents:UIControlEventTouchUpInside];
[loadButton setTag:1000];
[cell.contentView addSubview:loadButton];
}
if([indexPath section] == 1) {
//
// Mode Settings
//
if([indexPath row] == 0) {
cell.text = [mode objectAtIndex:[indexPath row]];
}
if([indexPath row] == 1) {
cell.text = [mode objectAtIndex:[indexPath row]];
}
}
if([indexPath section] == 2) {
//
// Marker Settings
//
if([indexPath row] == 0) {
// switch
UISwitch *markerSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[markerSwitch setOn:YES animated:NO];
[markerSwitch addTarget:self action:#selector(markerToggle:) forControlEvents:UIControlEventValueChanged];
[markerSwitch setTag:3000];
[cell.contentView addSubview:markerSwitch];
[markerSwitch release];
}
if([indexPath row] == 1) {
// slider
UISlider *markerGridSlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0, 10.0, 284, 10.0)];
markerGridSlider.minimumValueImage = [UIImage imageNamed:#"size_icon_1x1.png"];
markerGridSlider.maximumValueImage = [UIImage imageNamed:#"size_icon_8x8.png"];
[markerGridSlider setMinimumValue:1.0];
[markerGridSlider setMaximumValue:8.0];
[markerGridSlider setValue:8.0];
[markerGridSlider addTarget:self action:#selector(markerGrid:) forControlEvents:UIControlEventValueChanged];
[markerGridSlider setTag:3100];
[cell.contentView addSubview:markerGridSlider];
[markerGridSlider release];
}
if([indexPath row] == 2) {
// slider
UISlider *markerSpacingSlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0, 10.0, 284, 10.0)];
markerSpacingSlider.minimumValueImage = [UIImage imageNamed:#"spacing_icon_min.png"];
markerSpacingSlider.maximumValueImage = [UIImage imageNamed:#"spacing_icon_max.png"];
[markerSpacingSlider setMinimumValue:1.0];
[markerSpacingSlider setMaximumValue:(320.0/8.0)];
[markerSpacingSlider setValue:1.0];
[markerSpacingSlider addTarget:self action:#selector(markerSpacing:) forControlEvents:UIControlEventValueChanged];
[markerSpacingSlider setTag:3200];
[cell.contentView addSubview:markerSpacingSlider];
[markerSpacingSlider release];
}
}
} // end cell == nil
// Load
UIButton *loadButton = (UIButton*)[cell.contentView viewWithTag:1000];
[loadButton setTitle:#"Load Image" forState:UIControlStateNormal];
[loadButton setTitle:#"Load Image" forState:UIControlStateSelected];
// Mode
// Marker
UISwitch *markerSwitch = (UISwitch*)[cell.contentView viewWithTag:3000];
UISlider *markerGridSlider = (UISlider*)[cell.contentView viewWithTag:3100];
UISlider *markerSpacingSlider = (UISlider*)[cell.contentView viewWithTag:3200];
return cell;
}
All the cells bound to a UITable in iOS are reusable.
this is why you first get your cell with the function call "dequeueReusableCellWithIdentifier", the cell might not be nil, pointing to a cell that was loaded before. in your case, even if the cell is not nil, you add subviews to it. this will happen infinite times as you scroll up and down.
Here is a small example:
-(int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString* CellIdentifier = #"Cell";
const NSInteger lblTag = 101;
const NSInteger btnTag = 102;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//First init the cells
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//Initialize subviews of cells only in this block.
if (indexPath.row == 0) {
//Only the first cell on the top has a UILabel
UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 100, 20)] autorelease];
lbl.tag = lblTag;
[cell.contentView addSubview:lbl];
} else if (indexPath.row == 1) {
//Only the 2nd cell has a UIButton
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(5, 5, 60, 20);
btn.tag = btnTag;
[cell.contentView addSubview:btn];
}
}
//Modify your cells here
if (indexPath.row == 0) {
//Only the first cell on the top has a UILabel
UILabel *lbl = (UILabel*)[cell.contentView viewWithTag:lblTag];
//Do stuff with our label
lbl.text = [NSString stringWithFormat:#"%d",indexPath.row];
} else if (indexPath.row == 1) {
//Only the 2nd cell has a UIButton
UIButton *btn = (UIButton*)[cell.contentView viewWithTag:btnTag];
//Do stuff with our button
[btn setTitle:[NSString stringWithFormat:#"%d",indexPath.row] forState:UIControlStateNormal];
}
return cell;
}
In your very specific case, you would write this-
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
return 1;
} else if (section == 1) {
return 2;
} else if (section == 2) {
return 3;
} else {
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
const NSInteger
sec0BtnTag = 101,
markerSwitchTag = 102,
markerGridSliderTag = 103,
markerSpacingSliderTag = 104;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if([indexPath section] == 0) {
//
// Load Settings
//
// button
UIButton *loadButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] autorelease];
loadButton.frame = CGRectMake(0.0, 0.0, 300.0, 44.0);
[loadButton addTarget:self action:#selector(loadImage:) forControlEvents:UIControlEventTouchUpInside];
[loadButton setTag:sec0BtnTag];
[cell.contentView addSubview:loadButton];
}
else if([indexPath section] == 2) {
//
// Marker Settings
//
if([indexPath row] == 0) {
// switch
UISwitch *markerSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[markerSwitch setOn:YES animated:NO];
[markerSwitch addTarget:self action:#selector(markerToggle:) forControlEvents:UIControlEventValueChanged];
[markerSwitch setTag:markerSwitchTag];
[cell.contentView addSubview:markerSwitch];
[markerSwitch release];
}
else if([indexPath row] == 1) {
// slider
UISlider *markerGridSlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0, 10.0, 284, 10.0)];
markerGridSlider.minimumValueImage = [UIImage imageNamed:#"size_icon_1x1.png"];
markerGridSlider.maximumValueImage = [UIImage imageNamed:#"size_icon_8x8.png"];
[markerGridSlider setMinimumValue:1.0];
[markerGridSlider setMaximumValue:8.0];
[markerGridSlider setValue:8.0];
[markerGridSlider addTarget:self action:#selector(markerGrid:) forControlEvents:UIControlEventValueChanged];
[markerGridSlider setTag:markerGridSliderTag];
[cell.contentView addSubview:markerGridSlider];
[markerGridSlider release];
}
else if([indexPath row] == 2) {
// slider
UISlider *markerSpacingSlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0, 10.0, 284, 10.0)];
markerSpacingSlider.minimumValueImage = [UIImage imageNamed:#"spacing_icon_min.png"];
markerSpacingSlider.maximumValueImage = [UIImage imageNamed:#"spacing_icon_max.png"];
[markerSpacingSlider setMinimumValue:1.0];
[markerSpacingSlider setMaximumValue:(320.0/8.0)];
[markerSpacingSlider setValue:1.0];
[markerSpacingSlider addTarget:self action:#selector(markerSpacing:) forControlEvents:UIControlEventValueChanged];
[markerSpacingSlider setTag:markerSpacingSliderTag];
[cell.contentView addSubview:markerSpacingSlider];
[markerSpacingSlider release];
}
}
} // end cell == nil
//Load specific cell row values
if([indexPath section] == 0) {
//
// Load Settings
//
// button
UIButton *loadButton = (UIButton*)[cell.contentView viewWithTag:sec0BtnTag];
[loadButton setTitle:#"Load Image" forState:UIControlStateNormal];
[loadButton setTitle:#"Load Image" forState:UIControlStateSelected];
//do other stuff with the button here according to the specific row & section
}
if([indexPath section] == 1) {
//
// Mode Settings
//
if([indexPath row] == 0) {
cell.text = [mode objectAtIndex:[indexPath row]];
}
if([indexPath row] == 1) {
cell.text = [mode objectAtIndex:[indexPath row]];
}
}
if([indexPath section] == 2) {
//
// Marker Settings
//
if([indexPath row] == 0) {
// switch
UISwitch *markerSwitch = (UISwitch*)[cell.contentView viewWithTag:markerSwitchTag];
//do stuff with the switch here according to the specific row & section
}
if([indexPath row] == 1) {
// slider
UISlider *markerGridSlider = (UISlider*)[cell.contentView viewWithTag:markerGridSliderTag];
//do stuff with the slider here according to the specific row & section
}
if([indexPath row] == 2) {
// slider
UISlider *markerSpacingSlider = (UISlider*)[cell.contentView viewWithTag:markerSpacingSliderTag];
//do stuff with the slider here according to the specific row & section
}
}
return cell;
}
change static NSString *CellIdentifier = #"Cell"; for each section like:
NSString *CellIdentifier;
if(indexPath.section==0){ CellIdentifier= #"Cell"; }elseif(indexPath.section==2){ CellIdentifier=#"Cell2"; }

how can i make a uitableview container to bounce within the view

ok, so this is pretty simple one, but i hope i could explain this clearly - i have a table view that i would like to inset into a container, and then have the table bounces when it reaches the top / bottom. So far, I was able to put my table in a container, but the container is fixed on the view, while the table inside the container bounces. Again, I am looking for a way to fix the table to the container, while having the container bouncing.
Here is what I was able to do, following the code:
What I want to accomplish is to have the black box bouncing rather than the table within it.
my ViewDidLoad in the view controller .m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//General View Setup
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"backgroundimage.png"]];
self.view.backgroundColor = background;
//Table View Data
listOfItems = [[NSMutableArray alloc] init];
NSArray *appleComputers = [NSArray arrayWithObjects:#"iPhone",#"iPod",#"MacBook",#"MacBook Pro",nil];
NSDictionary *appleComputersDict = [NSDictionary dictionaryWithObject:appleComputers forKey:#"Computers"];
NSArray *otherComputers = [NSArray arrayWithObjects:#"HP", #"Dell", #"Windows", #"Sony", #"Ivory", #"IBM", nil];
NSDictionary *otherComputersDict = [NSDictionary dictionaryWithObject:otherComputers forKey:#"Computers"];
[listOfItems addObject:appleComputersDict];
[listOfItems addObject:otherComputersDict];
self.navigationItem.title = #"Computers";
// Create a table
tblSimpleTable.delegate = self;
CGRect cgRct = CGRectMake(10, 50, 300, 300);
tblSimpleTable = [[UITableView alloc] initWithFrame:cgRct style:UITableViewStyleGrouped]; // Initilize the table
[tblSimpleTable setBackgroundColor:[UIColor blackColor]];
tblSimpleTable.sectionHeaderHeight = 30.0;
tblSimpleTable.sectionFooterHeight = 30.0;
tblSimpleTable.delegate = self;
tblSimpleTable.dataSource = self;
[self.view addSubview:tblSimpleTable];
//Create the header
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 40)];
headerLabel.text = NSLocalizedString(#"Header for the table", #"");
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor yellowColor];
headerLabel.shadowOffset = CGSizeMake(0, 1);
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
self.tblSimpleTable.tableHeaderView = containerView;
}
why don’t you use UIScrollView for that.
I had tested your code & done required changes. Hope you like it.
Code :
(this is your .h file)
#import <UIKit/UIKit.h>
#interface tableScrollViewController : UIViewController
<UITableViewDelegate,UITableViewDataSource, UIScrollViewDelegate> {
UITableView *tblSimpleTable;
NSMutableArray *listOfItems;
NSMutableArray *appleComputers,*otherComputers;
UIScrollView *scrollView;
}
#end
(this is your .m file)
- (void)viewDidLoad {
[super viewDidLoad];
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
scrollView.delegate = self;
scrollView.backgroundColor = [UIColor grayColor];
scrollView.contentSize = CGSizeMake(300, 800);
appleComputers = [[NSMutableArray alloc] init]; // I made it by my style
[appleComputers addObject: #"iPhone"];
[appleComputers addObject:#"iPod"];
[appleComputers addObject:#"MacBook"];
[appleComputers addObject:#"MacBook Pro"];
otherComputers = [[NSMutableArray alloc] init];
[otherComputers addObject: #"HP"];
[otherComputers addObject:#"Dell"];
[otherComputers addObject:#"Windows"];
[otherComputers addObject:#"Sony"];
[otherComputers addObject:#"Ivory"];
[otherComputers addObject:#"IBM"];
self.navigationItem.title = #"Computers";
// Create a table
tblSimpleTable.delegate = self;
CGRect cgRct = CGRectMake(10, 50, 300, 600);
tblSimpleTable = [[UITableView alloc] initWithFrame:cgRct
style:UITableViewStyleGrouped]; // Initilize the table
[tblSimpleTable setBackgroundColor:[UIColor blackColor]];
tblSimpleTable.sectionHeaderHeight = 30.0;
tblSimpleTable.sectionFooterHeight = 30.0;
tblSimpleTable.scrollEnabled = NO;
tblSimpleTable.delegate = self;
tblSimpleTable.dataSource = self;
[scrollView addSubview:tblSimpleTable];
self.view = scrollView;
//Create the header
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 40)];
headerLabel.text = NSLocalizedString(#"Header for the table", #"");
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor yellowColor];
headerLabel.shadowOffset = CGSizeMake(0, 1);
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
tblSimpleTable.tableHeaderView = containerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section == 0)
return [appleComputers count];
else if(section == 1)
return [otherComputers count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.section == 0)
cell.text = [NSString stringWithFormat:#"%#“,
[appleComputers objectAtIndex:indexPath.row]];
else if(indexPath.section == 1)
cell.text = [NSString stringWithFormat:#"%#“,
[otherComputers objectAtIndex:indexPath.row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
// do whatever here
}

Remove top shadow in my grouped UITableView?

I am a little OCD and this is driving me insane. I have been messing around with these settings for a long time.
I have a UITableView grouped that I have a shadow on the top. When you tap the top cell, it removes. What gives?
I've been stressing over this for the past hour or so. Is there a simple solution for this? Or am I just going insane?
Thanks,
Coulton
EDIT:
viewDidLoad:
formTableView.backgroundColor = [UIColor clearColor];
formTableView.layer.borderColor = [UIColor clearColor].CGColor;
formTableView.separatorColor = [UIColor colorWithRed:(194.0 / 255.0) green:(194.0 / 255.0) blue:(194.0 / 255.0) alpha: 1];
Here is how I display my cells. WARNING: It's a lot of code. There's a bunch of stuff in there you will have to sort through, so sort through it at your own risk! :)
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleNone;
}
// What to do when you click delete.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
return NO;
}
//RootViewController.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return [formDataOne count];
} else {
return [formDataTwo count];
}
}
//RootViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
// Set up the cell...
NSString *cellValue;
if (indexPath.section == 0) {
cellValue = [formDataOne objectAtIndex:indexPath.row];
} else {
cellValue = [formDataTwo objectAtIndex:indexPath.row];
}
if (indexPath.section == 0) {
cell.text = #"";
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.row == 0) {
addTitle = [[UITextField alloc] initWithFrame:CGRectMake(13, 13, 280, 20)];
addTitle.borderStyle = UITextBorderStyleNone;
addTitle.textColor = [UIColor blackColor]; //text color
addTitle.font = [UIFont systemFontOfSize:16.0]; //font size
addTitle.placeholder = #"Album Name"; //place holder
addTitle.backgroundColor = [UIColor clearColor]; //background color
addTitle.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
addTitle.keyboardType = UIKeyboardTypeDefault; // type of the keyboard
addTitle.returnKeyType = UIReturnKeyDone; // type of the return key
addTitle.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
addTitle.delegate = self; // let us be the delegate so we know when the keyboard's "Done" button is pressed
[cell.contentView addSubview:addTitle];
} else if (indexPath.row == 1) {
// Set up loading text and show it
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 13, 280, 20)];
myLabel.text = #"Private Album";
myLabel.textColor = [UIColor blackColor];
myLabel.textAlignment = UITextAlignmentLeft;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.font = [UIFont fontWithName:#"Helvetica" size: 16.0];
myLabel.numberOfLines = 0;
//[myLabel sizeToFit];
privateSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[privateSwitch addTarget:self action:#selector(switchToggled:) forControlEvents: UIControlEventTouchUpInside];
[cell.contentView addSubview:privateSwitch];
//[privateSwitch setOn:NO animated:NO];
if ([howToDisplay isEqualToString:#"no"]) {
[privateSwitch setOn:NO animated:NO];
} else {
[privateSwitch setOn:YES animated:NO];
}
[cell.contentView addSubview:myLabel];
} else {
// Set up loading text and show it
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 13, 280, 20)];
myLabel.text = #"Comments";
myLabel.textColor = [UIColor blackColor];
myLabel.textAlignment = UITextAlignmentLeft;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.font = [UIFont fontWithName:#"Helvetica" size: 16.0];
myLabel.numberOfLines = 0;
//[myLabel sizeToFit];
[cell.contentView addSubview:myLabel];
commentsSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:commentsSwitch];
[commentsSwitch setOn:YES animated:NO];
}
} else {
//cell.text = cellValue;
UILabel *labelOne = [[UILabel alloc] initWithFrame:CGRectMake(48, 12, 130, 20)];
labelOne.text = cellValue;
labelOne.textColor = [UIColor blackColor];
[labelOne setFont:[UIFont boldSystemFontOfSize:16]];
labelOne.textAlignment = UITextAlignmentLeft;
labelOne.backgroundColor = [UIColor clearColor];
//labelOne.font = [UIFont fontWithName:#"Helvetica"];
labelOne.numberOfLines = 0;
[cell.contentView addSubview:labelOne];
if (indexPath.row == 0) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
} else if (indexPath.row == 1) {
int countFacebook = [dataCeter.connectionFacebookArray count];
if (countFacebook == 0) {
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
} else {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
} else if (indexPath.row == 2) {
//} else if (indexPath.row == 3) {
} else if (indexPath.row == 3) {
int countTumblr = [dataCeter.connectionTumblrArray count];
if (countTumblr == 0) {
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
} else {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
} else if (indexPath.row == 4) {
} else if (indexPath.row == 5) {
} else {
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
}
// Set imageView with correct thumbnail
UIImage *theImage;
if ([cellValue isEqualToString:#"Facebook"]) {
theImage = [UIImage imageNamed:#"icon_small_facebook.png"];
int countFacebook = [dataCeter.connectionFacebookArray count];
NSLog(#"facebook? %d // %#", countFacebook, dataCeter.connectionFacebookArray);
if (countFacebook != 0) {
facebookSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:facebookSwitch];
[facebookSwitch setOn:YES animated:NO];
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
} else if ([cellValue isEqualToString:#"Twitter"]) {
theImage = [UIImage imageNamed:#"icon_small_twitter.png"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else if ([cellValue isEqualToString:#"Flickr"]) {
theImage = [UIImage imageNamed:#"icon_small_flickr.png"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else if ([cellValue isEqualToString:#"Tumblr"]) {
theImage = [UIImage imageNamed:#"icon_small_tumblr.png"];
int countTumblr = [dataCeter.connectionTumblrArray count];
if (countTumblr != 0) {
tumblrSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:tumblrSwitch];
[tumblrSwitch setOn:YES animated:NO];
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
} else if ([cellValue isEqualToString:#"Email"]) {
theImage = [UIImage imageNamed:#"icon_small_email.png"];
int countEmail = [dataCeter.connectionEmailArray count];
} else if ([cellValue isEqualToString:#"MMS"]) {
theImage = [UIImage imageNamed:#"icon_small_mms.png"];
int countMMS = [dataCeter.connectionSMSArray count];
} else if ([cellValue isEqualToString:#"Photostream"]) {
theImage = [UIImage imageNamed:#"icon_small_photostream.png"];
cell.accessoryType = UITableViewCellAccessoryNone;
photostreamSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)];
[cell.contentView addSubview:photostreamSwitch];
[photostreamSwitch setOn:YES animated:NO];
} else {
theImage = nil;
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.imageView.image = theImage;
return cell;
}
Set your table view's separator style to UITableViewCellSeparatorStyleSingleLine. It's currently being set to UITableViewCellSeparatorStyleSingleLineEtched, which gives the effect of a doubled top border on the iPhone (it looks more detailed on iOS 5, and on iOS 3.2 and 4 on the iPad).
You're not insane, it looks like there is an extra pixel in there.
Try taking out "Sharing" and see if it still happens. Curious to see if the shadow is on "Sharing" or the table itself.
If that's the case, then you know your header view has a problem, not the table view.

UITableViewCell - overlapping with previous cells contents

I have this wierd problem with my table
i Have about 20 cells to display
Each cell is about 84px in height
When i click no the cell, i have set a background colour
The first 4 cells are ok, but when i scroll down and click on the 5th cell, the content of each cell starts to overlap with some other content, usually content from 1st 4 cells.
I belive its some cell reusability or drawing issue. Am not sure how to solve it, i have checked through my code, but i am not changing the cell's content on touch.
Here is my code and will add some pics too
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 104;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stores count];
}
-(UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CGRect Label1Frame = CGRectMake(5, 5, 250, 30);
CGRect Label2Frame = CGRectMake(6, 42, 220, 20);
CGRect Label3Frame = CGRectMake(6, 62, 220, 20);
CGRect Label4Frame = CGRectMake(240,56, 70, 12);
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}else{
// a cell is being recycled, remove the old edit field (if it contains one of our tagged edit fields)
UIView *viewToCheck = nil;
viewToCheck = [cell.contentView viewWithTag:1];
if (!viewToCheck) {
[viewToCheck removeFromSuperview];
DebugLog(#"View removed");
}
}
//cell.selectionStyle=UITableViewCellSelectionStyleNone;
[cell setSelectedBackgroundView:bgView];
NSInteger row=indexPath.row;
UILabel *lblTemp;
[[cell contentView] clearsContextBeforeDrawing];
//Line 1
lblTemp=[[UILabel alloc] initWithFrame: Label1Frame];
lblTemp.tag=1;
lblTemp.text=[[stores objectAtIndex:row] objectAtIndex:0] ;
lblTemp.numberOfLines=2;
lblTemp.font = [UIFont boldSystemFontOfSize:13];
lblTemp.adjustsFontSizeToFitWidth=YES;
lblTemp.minimumFontSize=12;
lblTemp.textColor = [UIColor grayColor];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Line 2
lblTemp = [[UILabel alloc] initWithFrame:Label2Frame];
lblTemp.tag = 2;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:1];
lblTemp.font = [UIFont systemFontOfSize:12];
lblTemp.textColor = [UIColor grayColor ];
lblTemp.textAlignment=UITextAlignmentLeft;
lblTemp.adjustsFontSizeToFitWidth=YES;
lblTemp.minimumFontSize=12;
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Line 3
lblTemp = [[UILabel alloc] initWithFrame:Label3Frame];
lblTemp.tag = 3;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:2];
lblTemp.font = [UIFont systemFontOfSize:12];
lblTemp.textColor = [UIColor grayColor ];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Phone button
UIButton *phoneButton=[[UIButton alloc] initWithFrame:CGRectMake(240,16,30,30)];
[phoneButton setBackgroundImage:[UIImage imageNamed:#"phone.png"] forState:UIControlStateNormal];
[phoneButton setTag:row];
[phoneButton addTarget:self action:#selector(dialNumber:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:phoneButton];
//ANnotation button
UIButton *annotation=[[UIButton alloc] initWithFrame:CGRectMake(274,16,30,30)];
[annotation setTag:row];
[annotation setBackgroundImage:[UIImage imageNamed:#"tab.png"] forState:UIControlStateNormal];
[annotation addTarget:self action:#selector(openMap:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:annotation];
[annotation release];
//Distance label
//Line 3
lblTemp = [[UILabel alloc] initWithFrame:Label4Frame];
lblTemp.tag = 4;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:5];
lblTemp.textAlignment=UITextAlignmentCenter;
lblTemp.font = [UIFont systemFontOfSize:13];
lblTemp.textColor = [UIColor grayColor ];
[lblTemp setAdjustsFontSizeToFitWidth:YES];
[cell.contentView addSubview:lblTemp];
[phoneButton release];
[lblTemp release];
[cell setNeedsLayout];
[cell setNeedsDisplay];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath ];
for(UILabel *lbl in cell.contentView.subviews){
if([lbl isKindOfClass:[UILabel class]]){
lbl.textColor=[UIColor whiteColor];
}
}
//UITableViewCell *cell1;
//NSString *row=[NSString stringWithFormat:#"%d",indexPath.row];
svm = [[storesMapView alloc] initWithNibName:#"storesMapView" bundle:nil];
[svm initWithXML:stores:indexPath.row];
CGRect theFrame = svm.view.frame;
theFrame.origin = CGPointMake(self.view.frame.size.width, 0);
svm.view.frame = theFrame;
theFrame.origin = CGPointMake(0,0);
theFrame.size=CGSizeMake(320,355);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3f];
svm.view.frame = theFrame;
[UIView commitAnimations];
[subView addSubview:svm.view];
backButton.hidden=NO;
}
I figured it out with some trial and error; if this can help some one
In cellforRowAtIndexPath i tried to clear all the cells subview before drawing the cell
//TRY TO REMOVE ALL CONTENT
for(UIView *view in cell.contentView.subviews){
if ([view isKindOfClass:[UIView class]]) {
[view removeFromSuperview];
}
}
I would be happy if someone can point me to some easier way
Thanks
You can use
[[[cell contentView] subviews] makeObjectsPerformSelector: #selector(removeFromSuperview)];
If the cell in not nil, the above code will reduce the time for using the for loop similar to this
for(UIView *eachView in [cell subviews])
[eachView removeFromSuperview];
I also had the same issue.I also had composed tableView with labels.And when I scroll it down the contents got overlapped.But it got solved simply by editing one statement in cellForRowAtIndexPath.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
I think this will solve your problem.
I know this is a bit late, but I had a similar issue where UILabels created for a cell were still part of the cell when it was reused. So each successive update of the tableview created another UILabel on top of the existing one. I moved the creation of the Labels into the if condition as below and it resolved my issue. Hope it helps someone else. Also note no release as I am using ARC.
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cityText = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
cityText.font = [UIFont fontWithName:#"Arial" size:20];
cityText.textAlignment = UITextAlignmentLeft;
cityText.backgroundColor = [UIColor clearColor];
regionText = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 100, 20)];
regionText.font = [UIFont fontWithName:#"Arial" size:20];
regionText.textAlignment = UITextAlignmentLeft;
regionText.backgroundColor = [UIColor clearColor];
}
Setting nil to label text on UITableViewCell subclass 's method prepareForReuse() solved my problem -
override func prepareForReuse() {
super.prepareForReuse()
self.label1.text = nil
self.label2.text = nil
....
}
Shared if it helps anyone!