Reused cell keeps getting double labels - ios

So, I'm trying to implement a UITableView with custom cells. However, when I scroll text is being overlaid on other text in reused cells.
This is how I construct the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * reuseIdentifier = #"programmaticCell";
MGSwipeTableCell * cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (!cell) {
cell = [[MGSwipeTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}
CGFloat brightness = [UIScreen mainScreen].brightness;
if (brightness < 0.4) {
cell.backgroundColor = [UIColor darkGrayColor];
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
}
NSString *imageUrl = [NSString stringWithFormat: #"%#", [self.streams[indexPath.row] plaatje]];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 55, 55)];
__block UIActivityIndicatorView *activityIndicator;
__weak UIImageView *weakImageView = image;
[image sd_setImageWithURL: imageUrl
placeholderImage:[UIImage imageNamed:#"tile-blue.png"]
options:SDWebImageProgressiveDownload
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
if (!activityIndicator) {
[weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
activityIndicator.center = weakImageView.center;
[activityIndicator startAnimating];
}
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
[activityIndicator removeFromSuperview];
activityIndicator = nil;
}];
UIView *cellView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 65)];
[cellView addSubview:image ];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 15, self.view.frame.size.width, 20)];
nameLabel.text = [[self.streams[indexPath.row] name] capitalizedString];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.font = [UIFont systemFontOfSize:20];
UILabel *publishLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 35, 100, 20)];
publishLabel.text = [[self.streams[indexPath.row] published] capitalizedString];
publishLabel.textAlignment = NSTextAlignmentLeft;
publishLabel.font = [UIFont systemFontOfSize:13];
if (brightness < 0.4) {
nameLabel.textColor = [UIColor whiteColor];
publishLabel.textColor = [UIColor whiteColor];
} else {
nameLabel.textColor = [UIColor blackColor];
publishLabel.textColor = [UIColor blackColor];
}
[cellView addSubview:nameLabel];
[cellView addSubview:publishLabel];
[cell addSubview:cellView];
[cell sendSubviewToBack:cellView];
cell.delegate = self; //optional
return cell;
}
And this is MGSwipeTableCell's prepareForReuse method that I rewrote:
-(void) prepareForReuse
{
[super prepareForReuse];
self.textLabel.text = nil;
self.detailTextLabel.text = nil;
self.imageView.image = nil;
[self cleanViews];
BOOL cleanButtons = _delegate && [_delegate respondsToSelector:#selector(swipeTableCell:swipeButtonsForDirection:swipeSettings:expansionSettings:)];
[self initViews:cleanButtons];
}
What am I doing wrong here?

Every time your method is called, you try to dequeue a cell. This is correct.
However, all of your code after that assumes you're getting a new cell, which is incorrect. You're making new labels each time, and adding them to the cell each time, when the dequeued cells already have these labels.
Either use viewWithTag: to check if the labels are there (and only create them if they're not), or make a custom table cell subclass with properties for each label.
Your implementation of tableview:cellForRowAtIndexPath: needs to be idempotent, meaning you should write your code so that it can be called multiple times over and over, and always return an identical cell.

Your problem may be because you are recreating the items for the cells every time.
Try sub-classing UITableViewCell and move all of your code into it. Set up properties for all of your labels/imageViews/etc. You can even create an xib and use autolayout with IBOutlets to manage the way the cell looks.
If you end up creating an xib though, just be aware that you have to register the nib in your tableView class before you can use it.
self.tableView registerNib:[UINib nibWithNibName:#"nameOfXibFile" bundle:nil]; forCellReuseIdentifier:#"customIdentifier"];
When you do this, it will be referencing the same label/image/etc objects each time it reuses the cell and won't be creating new objects.

Related

UITableview overwriting on olddata

hi im creating chat example and if user add send button adding new object in my arrray and reload data but its overwrite old table.
its my array :
arr1 = [[NSMutableArray alloc] initWithObjects:#"Whats up today ? ", #"Hello.", nil];
Here my source :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simleTableIdentifier = #"TeamCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"TeamCell"];
}
cell.backgroundColor = [UIColor clearColor];
tableView.scrollEnabled = YES;
UIImageView *myRect = [[UIImageView alloc] initWithFrame:CGRectMake(20, 30, 10, 12)];
myRect.image = [UIImage imageNamed:#"tri.png"];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"jj.jpg"]];
UILabel *label = [[UILabel alloc] init];
label.text = [arr1 objectAtIndex:indexPath.row];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font =[UIFont systemFontOfSize:14.0];
label.text = [arr1 objectAtIndex: indexPath.row];
label.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor clearColor];
label.frame = CGRectMake(40, 40, 210, 80);
[label sizeToFit];
UIImageView *imgim = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, label.frame.size.width+20, label.frame.size.height+20)];
imgim.image = [UIImage imageNamed:#"bg.png"];
CGRect myRectANGLE = CGRectMake(imgim.frame.origin.x+10,imgim.frame.origin.y+10, label.frame.size.width, label.frame.size.height);
[label setFrame:myRectANGLE];
CALayer *addRadius = [imgim layer];
[addRadius setMasksToBounds:YES];
[addRadius setCornerRadius:5.0];
[self.MyTableView setSeparatorColor:[UIColor clearColor]];
[self.MyTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
self.MyTableView.transform = CGAffineTransformMakeScale(1, -1); //in viewDidLoad
cell.transform = CGAffineTransformMakeScale(1, -1);//in tableView:cellForRowAtIndexPath:
[[cell contentView] addSubview:myRect];
[[cell contentView] addSubview:imgim];
[[cell contentView] addSubview:label];
return cell;
}
İf click send button i reload data but its overwite on old-data look like my photo :
-(IBAction)btnTap:(UIButton *)sender {
[arr1 insertObject:Textify.text atIndex:0];
NSLog(#"%i", arr1.count);
[MyTableView reloadData];
}
Try clearing the cell's contentView subview, and then add the new subviews.
Here's a block of code for removing the subviews, taken from this post.
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
UITableViewCell will be reused while reload, you should not create subviews again to add on cell.contentView.Try to use code below
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"TeamCell"];
UILabel *label = [[UILabel alloc] initWithFrame:someFrame];
label.tag = 1000;
[cell.contentView addSubview:label];
}
UILabel *label = [cell.contentView viewWithTag:1000];
label.text = #"something";

Tableview is not displaying any cells or rows content in new pushed viewController

I'm not sure what I'm missing but I'm trying to display a new viewController and passing some data to it, but the problem is when this new viewController gets pushed it doesn't display the cells or rows content like labels, textfields and so on..
This is how I'm pushing from one controller to another..
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BillComparatorViewController *vc = [[BillComparatorViewController alloc] init];
vc.selectedInstitution = [self.myInstitution objectAtIndex:indexPath.row];
vc.managedObjectContext = self.managedObjectContext;
[self.view endEditing:YES];
[self.navigationController pushViewController:vc animated:YES];
}
Then in my new pushed view controller this is my cellForRowAtIndexPath function..
//UITableView Delegate + Datasource
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
for (UIView *view in cell.contentView.subviews)
[view removeFromSuperview];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor whiteColor];
cell.textLabel.text = [self.labels objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = [self.labels objectAtIndex:indexPath.row];
CGFloat i = [[self.rowHeights objectAtIndex:indexPath.row] floatValue];
UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 280, 15)];
cellLabel.font = [UIFont fontWithName:kFONTNAME size:kSystemFontSizeRows];
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UIButton class]]){
cell.textLabel.font = [UIFont fontWithName:kFONTNAME size:kSystemFontSizeRows];
cell.backgroundColor = [UIColor lightGrayColor];
[cell.contentView addSubview:[self.tableViewElements objectAtIndex:indexPath.row]];
[cell.contentView addSubview:arrow];
}
else if (i > kTableRowHeight)
{
cell.textLabel.text = nil;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kElementWidth/2, 75)];
lbl.text = [self.labels objectAtIndex:indexPath.row];
lbl.font = _myFont;
lbl.numberOfLines = 0;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:[self.tableViewElements objectAtIndex:indexPath.row]];
[cell.contentView addSubview:lbl];
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UISwitch class]])
{
[cell.contentView addSubview:[self.tableViewElements objectAtIndex:indexPath.row]];
}
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UITextField class]])
{
// Can make a class for this cell's contentview, however it never repeats in code
UITextField* txtField = [self.tableViewElements objectAtIndex:indexPath.row];
txtField.textColor = kBlueColor;
txtField.textAlignment = NSTextAlignmentLeft;
txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; // iOS 6 support
NSString *imageName = #"image";
NSString *arrowName = #"image1";
if (selectedRow == indexPath.row)
{
imageName = #"image";
arrowName = #"image1";
txtField.textColor = [UIColor whiteColor];
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2*kElementWidth/3 -12, 23, 135, 27)];
imgView.image = [UIImage imageNamed:imageName];
[cell.contentView addSubview:imgView];
UIImageView *arrowView = [[UIImageView alloc] initWithFrame:CGRectMake(kElementWidth+10, 31, 8.5, 10)];
arrowView.image = [UIImage imageNamed:arrowName];
[cell.contentView addSubview:arrowView];
[cell.contentView addSubview:txtField];
}
}
else
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = [self.labels objectAtIndex:indexPath.row];
cell.textLabel.font = _myFontSmall;
cell.textLabel.textColor = kBlueColor;
cell.textLabel.backgroundColor = [UIColor clearColor];
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UITextField class]])
{
// Can make a class for this cell's contentview, however it never repeats in code
UITextField* txtField = [self.tableViewElements objectAtIndex:indexPath.row];
txtField.textColor = kBlueColor;
txtField.textAlignment = NSTextAlignmentLeft;
txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; // iOS 6 support
NSString *imageName = #"image";
NSString *arrowName = #"image1";
if (selectedRow == indexPath.row)
{
imageName = #"image";
arrowName = #"image2";
txtField.textColor = [UIColor whiteColor];
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2*kElementWidth/3 -12, 12, 135, 27)];
imgView.image = [UIImage imageNamed:imageName];
[cell.contentView addSubview:imgView];
UIImageView *arrowView = [[UIImageView alloc] initWithFrame:CGRectMake(kElementWidth+10, 20, 8.5, 10)];
arrowView.image = [UIImage imageNamed:arrowName];
[cell.contentView addSubview:arrowView];
[cell.contentView addSubview:txtField];
}
if (isSearching)
{
cellLabel.text = [searchElements objectAtIndex:indexPath.row];
[cell.contentView addSubview:cellLabel];
}
}
return cell;
}
It's a bit long sorry but I think it was important to post it..
UPDATE
This is how the problem happens, when user select a row within the current viewcontroller didSelectRowAtIndexPath calls a new viewcontroller and pushes this controller but if the user does this while searching with the keyboard in the screen is when the problem happens that the new viewcontroller pushed doenst show any content in its tableview..
SOLVED
Within my cellForRowAtIndexPath
[cell setTranslatesAutoresizingMaskIntoConstraints:NO];
The issue is with Autolayout. I had the same problem with iOS 8 beta. (I know you're not using i OS 8 but still).
Try turning it off. Should sort the issue out.
i think the problem is initiating the object of BillComparatorViewController.
You do like this .You may get solution
BillComparatorViewController *vc = [[BillComparatorViewController alloc] initWithNibName:"BillComparatorViewController" Bundle:nil];

Add Arrays of (parse.com) to a UICollectionView SubView

I am trying to add a label (string array) from Parse.com into a subview that shows up after tapping an image inside a UICollectionViewCell.
The subview appears, and the text also but it's the same text in every subview of each cell. It is not changing..
The arrays in my dataBrowser are: precio_0, precio_1, precio_2 etc..
What am I doing wrong? How would the code go to recognize it is another cell. If I set the code in the UICollectionViewCell and not in the Subview there is no problem, the text changes in every view. So I'm missing something but don't know what it is.
**NOTE: This is the DetailView and the data is being passed as a property so to get the data the method goes: [self.vestimenta objectForKey:#"String"]
My code:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
VestimentaDetailCell *cell = (VestimentaDetailCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
[cell.activityIndicator startAnimating];
cell.imageFile.image = [UIImage imageNamed:#"LoadLook.png"];
PFFile *imageFile = [self.vestimenta objectForKey:[NSString stringWithFormat:#"image_%ld", (long)indexPath.row]];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error && data.length > 0) {
cell.imageFile.image = [UIImage imageWithData:data];
UITapGestureRecognizer *infoLook = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(handleTap:)];
infoLook.numberOfTapsRequired = 1;
[cell.imageFile addGestureRecognizer:infoLook];
} else {
[cell.progressView removeFromSuperview];
}
} progressBlock:^(int percentDone) {
float percent = percentDone * 0.02;
[cell.progressView setProgress:percent];
if (percentDone == 100){
[cell.progressView removeFromSuperview];
};
[cell.showInfo addTarget:self
action:#selector(handleTap:)
forControlEvents:UIControlEventTouchUpInside];
[cell.activityIndicator stopAnimating];
}];
return cell;
}
-(void)handleTap:(UITapGestureRecognizer *) infoLook{
CGRect frame = CGRectMake(0, 0, 320, 519);
UIView *infoView = [[UIView alloc] initWithFrame:frame];
infoView.opaque = NO;
infoView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8f];
infoView.userInteractionEnabled = YES;
infoView.tag = 01;
UIButton *priceTag = [[UIButton alloc] initWithFrame:CGRectMake(282, 370, 25, 25)];
[priceTag setImage:[UIImage imageNamed:#"Price.png"] forState:UIControlStateNormal];
UILabel *precioProductos = [[UILabel alloc] initWithFrame:CGRectMake(32, 370, 240, 190)];
precioProductos.textColor = [UIColor whiteColor];
precioProductos.backgroundColor = [UIColor clearColor];
precioProductos.textAlignment = NSTextAlignmentRight;
precioProductos.numberOfLines = 0;
precioProductos.font = [UIFont fontWithName:#"HelveticaNeue-LightItalic" size:15];
This part shows the calling of the arrays in Parse.com:
VestimentaDetailCell *price = (VestimentaDetailCell *)[precioProductos superview];
NSIndexPath *indexPath = [imagesCollection indexPathForCell:price];
NSMutableString *precio = [NSMutableString string];
for (NSString* precios in [self.vestimenta objectForKey:[NSString stringWithFormat:#"precios_%ld", (long)indexPath.row]]) {
[precio appendFormat:#"%#\n", precios];
}
precioProductos.text = precio;
[precioProductos sizeToFit];
CGRect myFrame = precioProductos.frame;
myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, 240, myFrame.size.height);
precioProductos.frame = myFrame;
[infoView addSubview:priceTag];
[infoView addSubview:precioProductos];
[self.view addSubview:infoView];
UITapGestureRecognizer *dismissView = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(processTap:)];
dismissView.numberOfTapsRequired = 1;
[infoView addGestureRecognizer:dismissView];
}

Add tableview cell with the value of UITextfield

I have a UITextField in a UITableView header. When the user enters anything in the UITextFields, the entry gets added to a NSMutableArray.
I want to create a new UITableCell with the value of the UITextField entry whenever textFieldShouldReturn is called.
I tried using reloadData but that seems to empty my array completely.
Any suggestions? Thanks
- (BOOL)textFieldShouldReturn:(UITextField *)task
{
[task resignFirstResponder];
[self.tasksArray addObject:task.text];
NSLog(#"Test %#", self.tasksArray);
}
My cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
SwipeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[SwipeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
[cell setDelegate:self];
[cell.contentView setBackgroundColor:[UIColor whiteColor]];
// Setting the default inactive state color to the tableView background color
[cell setDefaultColor:self.tableView.backgroundView.backgroundColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
[cell.textLabel setText:self.task.text];
self.view = tableView;
cell.mode = SwipeTableViewCellModeExit;
return cell;
}
My UITableView header :
- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section{
float width = tableView.bounds.size.width;
int fontSize = 18;
int padding = 1;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0,width, fontSize+11)];
view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
view.userInteractionEnabled = YES;
view.tag = section;
UITextField *task = [[UITextField alloc] initWithFrame:CGRectMake(padding, 2,
width - padding , fontSize + 11)];
task.text = #"Type here";
task.borderStyle = UITextBorderStyleRoundedRect;
task.textAlignment = NSTextAlignmentCenter;
task.backgroundColor = [UIColor whiteColor];
task.textColor = [UIColor blackColor];
task.delegate = self;
task.font = [UIFont boldSystemFontOfSize:fontSize];
[view addSubview:task];
self.tasksArray = [[NSMutableArray alloc] init];
return view;
}
viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
self.tasksArray = [NSMutableArray arrayWithCapacity:0];
self.title = #"Test";
self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[backgroundView setBackgroundColor:[UIColor colorWithRed:227.0 / 255.0
green:227.0 / 255.0
blue:227.0 / 255.0
alpha:1.0]];
[self.tableView setBackgroundView:backgroundView];
}
Remove [cell.textLabel setText:self.task.text];
And then,
Insert [self.yourTableOutletName reloadData]; after [self.tasksArray addObject:task.text];
Now your code will reload the tableView after adding a object into self.taskArray.
And then,
To reflect your array in tablView use this line.
Insert [cell.textLabel setText:[self.tasksArray objectAtIndex:indexPath.row]]; after [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
This line pulls the data incorrectly: [cell.textLabel setText:self.task.text];
self.view = tableView;
It should be from your array.
Also you never reload data, that should be the last line in textFieldShouldReturn

Different images in different cells of tableViewController are not working properly

I have made a tableViewController. I want to give different images to the 1st and 7th index cell. This is a code snippet inside my cellForRowAtIndexPath delegate method. It initializes the cells properly in the beginning but when I scroll up and down several times then it also starts to give the "button4.png" in the accessory view of other cells.
UIImage *indicatorImage;
if(indexPath.row==0||indexPath.row==6)
{
indicatorImage = [UIImage imageNamed:#"button4.png"];
}
else
{
indicatorImage = [UIImage imageNamed:#"img-arrow.png"];
}
cell.accessoryView =
[[UIImageView alloc]
initWithImage:indicatorImage];
What can be the possible reason for this?
The complete code of the function is a little messy, but I am posting it here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
selection=self.tabBarController.selectedIndex;
static NSString *CellIdentifier = #"Cell";
UILabel *topLabel;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImage *indicatorImage;
if(indexPath.row==0||indexPath.row==6)
{
indicatorImage = [UIImage imageNamed:#"button4.png"];
}
else
{
indicatorImage = [UIImage imageNamed:#"img-arrow.png"];
}
cell.accessoryView =
[[UIImageView alloc]
initWithImage:indicatorImage];
cell.accessoryView =
[[UIImageView alloc]
initWithImage:indicatorImage];
const CGFloat LABEL_HEIGHT = 20;
topLabel =
[[UILabel alloc]
initWithFrame:
CGRectMake(
2.0 * cell.indentationWidth,
0.5 * (tableView.rowHeight - 2 * LABEL_HEIGHT),
tableView.bounds.size.width -
4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)];
[cell.contentView addSubview:topLabel];
topLabel.backgroundColor = [UIColor clearColor];
topLabel.shadowColor = [UIColor whiteColor];
topLabel.shadowOffset = CGSizeMake(0, 1);
topLabel.textColor = [UIColor colorWithRed:0.0 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]];
topLabel.tag=10;
cell.backgroundView =
[[UIImageView alloc] init];
cell.selectedBackgroundView =
[[UIImageView alloc] init];
}
}
else
{
topLabel = (UILabel *)[cell viewWithTag:10];
}
UIImage *rowBackground;
UIImage *selectionBackground;
rowBackground = [UIImage imageNamed:#"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
if(indexPath.row==0||indexPath.row==6)
{
rowBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
topLabel.textColor = [UIColor colorWithRed:0.0 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:20];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
NSString *object = _objects[indexPath.row];
NSString *str=[object description];
topLabel.text=[NSString stringWithFormat:#" %#",str];
return cell;
}
You are setting this image in your if (cell == nil) ... block in which you create and configure the cell. But you need to move this image setting outside of that if block because if the cell is being reused (ie you don't have to alloc and init), the old image will be reused. You should review anything inside that if statement for things that should change cell-by-cell, and move that outside of the if block.
When scrolling messes you up like this, it suggests that you're not completely initializing the contents of a REUSED UITableViewCell. While your code snippet says you do set it to something -- your result suggests that you aren't. You can look for that.
For instance, try setting the accessoryView to nil immediately after getting the cell and see if the problem goes away.

Resources