UITableViewCell image changes when scrolling - iphone

I have a UITableView with a title and an image on each cell. Some cells will have a default image and others will not. When I scroll the table, the image of some rows is not the expected and the image of another row gets displayed instead of the expected one. If I don't use dequeuereuseidentifier everything works fine, but I want to use it because I have lots of cells.
Any suggestion?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
CGRect titleRect = CGRectMake(60, 6, 200, 24);
UILabel *title = [[UILabel alloc] initWithFrame: titleRect];
title.tag = 1;
title.backgroundColor = [UIColor clearColor];
title.font = [UIFont fontWithName:#"AdelleBasic-Bold" size:15.5];
[cell.contentView addSubview:title];
UIImageView *defaultCellImage = [[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 42, 42)];
defaultCellImage.tag = 2;
[defaultCellImage setImage:[UIImage imageNamed: #"Default_Row_Image"]];
[cell.contentView addSubview:defaultCellImage];
}
NSUInteger row = [indexPath row];
Movie *movie = [_movies objectAtIndex: row];
UILabel *titleRowLabel = (UILabel *) [cell.contentView viewWithTag:1];
titleRowLabel.text = [movie title];
UIImageView *cellImage = (UIImageView *) [cell.contentView viewWithTag:2];
if (![movie.imageName isEqualToString:#""])
[cellImage setImage:[UIImage imageNamed: [movie imageName]]];
return cell;
}

The first cells to be used in your table view will be properly loaded. Since there is no cell to dequeue, the if (cell == nil) will return YES and your cell will have its image set to be the default. Then, if your condition for setting a different image is satisfied later in the method, a different image will be shown. So far, so good.
However, when a reusable cell is dequeued, it already has an image set, which might not be the default. Since cell == nil will now return NO, this cell will never have its image reset to the default one, even if it is the image that should be shown.

Related

Button in UITableView is appearing twice in iPad Master View Controller

Created a UITableView programmatically, data in my tableview in iPad Master View Controller is loaded dynamically, i am putting a button in the last cell, but the button is showing up again in the tableview underneath the cell... First time when the code is executed, the button appears only once, but next time it shows up twice... Here is the 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];
}
if([_objects count] > 1)
{
if(indexPath.row == [_objects count])
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
button.frame = CGRectMake(cell.frame.origin.x + 50, cell.frame.origin.y + 15, 225, 30);
[button setTitle:#"Hide me" forState:UIControlStateNormal];
[button addTarget:self action:#selector(customActionPressed) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor= [UIColor clearColor];
[cell.contentView addSubview:button];
}
else
{
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.textColor = [UIColor colorWithRed:0/255.0 green:100.0/255.0 blue:220.0/255.0 alpha:1.0];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:13];
cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
NSLog(#"%#", [_objects objectAtIndex:indexPath.row]);
}
}
return cell;
}
for ex:: here is a snapshot of the tableview (how can i put the image here???)
aaa
bbb
ccc
ddd
eee
UIButton
UIButton is appearing again here in the tableview
Here is the image link http://s10.postimg.org/fwarb2661/i_OS_Simulator_Screen_shot_28_Dec_2013_10_57_32_A.png
any help is appreciated, thanks in advance..
Please write bellow code :
if (cell)
{
cell =nil;
}
before creating your tableview cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//write here
if (cell)
{
cell =nil;
}
//*
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
For set background image in cell plese use bellow code :-
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(X, Y, 277, 58)];
imageView.backgroundColor = [UIColor clearColor];
imageView.opaque = NO;
imageView.image = [UIImage imageNamed:#"yourImage.png"];
cell.backgroundView = imageView;
Probably because your table view is using the same cell again.
Make sure you delete the button from the cell every time.
Would help to see your code so I can point to you exact location...
Try this:
(void)prepareForReuse {
[super prepareForReuse];
}
In the method set the button to nil or any other elements showing twice. The cell is being reused and you need to run prepareForReuse to empty the old cells.

why tag changed in tableview to reuseing cells

I am creating custom cell contain UILabel , UIImageView ,using constant tag for UILabel , UIImageView using dynamic tag, the table have 11 cells, the first 7 cells loading correctly, the 8, 9, 10, 11 cell image view change when I am changing the 1, 2, 3, 4, cell respectively in the table, also the tags are same in the cells, I am using the images to check box in table,UITapGestureRecognizer used to change imageview in the table,
I am using this code.....
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier =#"Cell";
UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
cell.selectionStyle=UITableViewCellSelectionStyleGray;
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(5, 12, 20, 20)];
imageview.tag=n;
[cell.contentView addSubview:imageview];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tabimage:)];
imageview.userInteractionEnabled=YES;
[imageview addGestureRecognizer:tap];
imageview.image=[UIImage imageNamed:#"img1.jpeg"];
UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(30, 2, 260,26)];
titleLabel.tag=222;
titleLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:titleLabel];
UILabel *dateLabel=[[UILabel alloc]initWithFrame:CGRectMake(30, 31, 260, 13)];
dateLabel.tag=333;
dateLabel.font=[UIFont systemFontOfSize:10];
dateLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:dateLabel];
}
UIImageView *imageview1=(UIImageView*)[cell.contentView viewWithTag:n];
if([array containsObject:[NSNumber numberWithInt:imageview1.tag]]) {
imageview1.image=[UIImage imageNamed:#"img2.jpeg"];
} else {
imageview1.image=[UIImage imageNamed:#"img1.jpeg"];
}
UILabel *titlelable=(UILabel*)[cell.contentView viewWithTag:222];
titlelable.text=[task objectAtIndex:indexPath.section];
NSLog(#"%i",indexPath.section);
UILabel *dateLabel=(UILabel*)[cell.contentView viewWithTag:333];
dateLabel.text=[date objectAtIndex:indexPath.section];
n++;
return cell;
}
- (void)tabimage:(id)sender {
UIImageView *iv=(UIImageView *)[sender view];
int i=iv.tag;
NSLog(#"------------%i",i);
if (iv.image==[UIImage imageNamed:#"img1.jpeg"]) {
iv.image= [UIImage imageNamed:#"img2.jpeg"];
[array addObject:[NSNumber numberWithInt:i]];
} else {
iv.image= [UIImage imageNamed:#"img1.jpeg"];
[array removeObject:[NSNumber numberWithInt:i]];
}
}
You should change your cell identifier from static to dynamic that will solve your problem.
You should replace this
static NSString *CellIdentifier =#"Cell";
UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier];
with this
UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:[NSString stringWithFormat:#"%d %d"], indexPath.row, indexPath.section];
Whatever problem you see, use of that "n" is most probably the problem. There is no good reason to use a shared variable to tag (and retrieve) views on table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath is called many times, it may be called several times for the same cell, and sometimes it finds a cell to reuse, and sometimes not.
I have of course no idea what n is, and how you use it elsewhere in your code, but you change it with every call here, and you cannot make assumptions when this method is called, so it's worthless.
You know for sure that every cell has one image with that tag, but if it will ever be accessible after the first run through this method or not is totally undefined, so with every reuse you basically get random behavior (either a fresh new cell or a reused one with a tag you don't know).
Ask yourself (or maybe at SO in another question): What are you trying to accomplish here?
i am getting solution for my app,
to using dynamic cell identifier in my code
NSString *CellIdentifier =[NSString stringWithFormat:#"%i-%i", indexPath.section,indexPath.row];
I suggest subclass the UITableViewCell add there all your custom elements, create setters for it. And in cellForRowAtIndexPath just call your setters.
As you are setting tag to imageview in if(cell == nil) block means tag will be set when cell is getting created. In your case 7 cells are getting created after that cells are reused by dequeuing. Hence for 8 onwards previously created cells will be used. This is why your tags are same as 1,2,3...for 8,9,10...cells.
Well, Alex suggested standard way to do it. But if you have not used custom cells yet, you can try this-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier =#"Cell";
UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier];
UIImageView *imageview = nil;
if(cell){
for (UIView *view in cell.contentView.subviews){
if([view isKindOfClass:[UIImageView class]]){
imageview = (UIImageView*)view;
break;
}
}
}
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
cell.selectionStyle=UITableViewCellSelectionStyleGray;
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
imageview=[[UIImageView alloc]initWithFrame:CGRectMake(5, 12, 20, 20)];
[cell.contentView addSubview:imageview];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tabimage:)];
imageview.userInteractionEnabled=YES;
[imageview addGestureRecognizer:tap];
imageview.image=[UIImage imageNamed:#"img1.jpeg"];
UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(30, 2, 260,26)];
titleLabel.tag=222;
titleLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:titleLabel];
UILabel *dateLabel=[[UILabel alloc]initWithFrame:CGRectMake(30, 31, 260, 13)];
dateLabel.tag=333;
dateLabel.font=[UIFont systemFontOfSize:10];
dateLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:dateLabel];
}
imageview.tag=n;
if([array containsObject:[NSNumber numberWithInt:imageview.tag]]) {
imageview.image=[UIImage imageNamed:#"img2.jpeg"];
} else {
imageview.image=[UIImage imageNamed:#"img1.jpeg"];
}
UILabel *titlelable=(UILabel*)[cell.contentView viewWithTag:222];
titlelable.text=[task objectAtIndex:indexPath.section];
NSLog(#"%i",indexPath.section);
UILabel *dateLabel=(UILabel*)[cell.contentView viewWithTag:333];
dateLabel.text=[date objectAtIndex:indexPath.section];
n++;
return cell;
}

How to avoid over ride of labels which are added to cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 33)];
dataLabel = [[UILabel alloc]initWithFrame:CGRectMake(105, 0, 320, 33)];
timeLabel.backgroundColor = [UIColor clearColor];
dataLabel.backgroundColor = [UIColor clearColor];
dataLabel.textColor = [UIColor whiteColor];
timeLabel.textColor = [UIColor whiteColor];
[cell.contentView addSubview:timeLabel];
[cell.contentView addSubview:dataLabel];
if(indexPath.row == 0)
{
if([storedDataArray count]>0)
{
timeLabel.text = currenttime;
dataLabel.text = textView1.text;
}
return cell; //returns empty cell if there is no data in the data base
}
if(indexPath.row == 1)
{
timeLabel.text = currenttime;
dataLabel.text = textView2.text;
return cell;
}
I have a table view
- i want to display my textlabel on left side, just beside detailTextlabel.
actually when i use textLabel.text, DetailTextLabel.Text and alignments,
they displayed but not at the position i want.
so i tried to use own labels..
but they get overwritten.
since we did not (it's not possible to) change the possition & the frame size of the cell textlabel, detailTextLabel, i added 2 labels with a frame size that i want.
but when we entered text in text views and return back to table view.. the labels get overwritten..
what to do..
is there any alternate to fixed the frame size of my text label
or to avoid overwriting of our labels
Use Custom UITableViewCell instead. You can align and place labels easily using custom tabe cells.
This link will be helpful. http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7-SW1
look at the customizing section in the document.
use this code it will work perfectly
if (cell== nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuNameCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSLog(#"---------new cell agin");
}
else
{
NSArray *arrayView = [cell.contentView subviews];
for (UIView *vTemp in arrayView)
{
[vTemp removeFromSuperview];
}
NSLog(#"---No New Cell hiiii");
// Setting Tag To UIButton
_checkButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
_cancelButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
}
add else part only

UITableView problem with adding extra cell

First question on this site, although I have been around for a while behind the scenes. I have a problem that I have been racking my head on for the last two days and I hope someone can shed some light on it for me.
I have a UITableView, which is loaded from a SQL database. It has 15 entries in it. I have inserted an extra cell at the beginning of the UITableView. This extra cell is for a UITextField and UIButton which adds an item into the database.
When the view is loaded, the first cell with the custom objects shows fine, and the rest of the table is filled with items from the database and looks just how it should. However, when the UITableView is scrolled down so the first cell is out of view, then back up, it takes the value of the 11th row item and shows it over top the first cell.
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)popTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
static NSInteger NameTag = 1;
UITableViewCell *cell = [popTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
CGRect frame;
frame.origin.x =50;
frame.origin.y =10;
frame.size.height =22;
frame.size.width =275;
UILabel *nameLabel = [[UILabel alloc] initWithFrame:frame];
nameLabel.tag = NameTag;
nameLabel.opaque = YES;
nameLabel.textColor = [UIColor grayColor];
nameLabel.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:nameLabel];
[nameLabel release];
}
int row = [indexPath row];
if (row == 0) {
UIButton *buttonLeft = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonLeft setFrame: CGRectMake( 205, 6, 40, 33)];
[buttonLeft addTarget:self action:#selector(addToList:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:buttonLeft];
//No Alloc for txtField, it is built in IB
[txtField setBorderStyle:UITextBorderStyleNone];
[txtField setFrame: CGRectMake( 17, 12, 180, 23)];
txtField.backgroundColor = [UIColor clearColor];
[txtField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
txtField.clearButtonMode = UITextFieldViewModeAlways;
}else{
UILabel * nameLabel = (UILabel *) [cell.contentView viewWithTag:NameTag];
Add *theObj = [self.theArray objectAtIndex:indexPath.row - 1];
[nameLabel setText:theObj.itemName];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImageView *imageView = [cell viewWithTag:kTagCellImageView];
if (imageView == nil) {
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10.0, 10.0, 13.0, 25.0)];
imageView.backgroundColor = [UIColor clearColor];
imageView.tag = kTagCellImageView;
[cell.contentView addSubview:imageView];
}
if([theObj.itemName isEqualToString:#"First Street"]){
imageView.frame = CGRectMake(14,10,13,25);
[imageView setImage:[UIImage imageNamed:#"firststreet"]];
}
else if([theObj.itemName isEqualToString:#"Second Street"]){
imageView.frame = CGRectMake(8,12,29,20);
[imageView setImage:[UIImage imageNamed:#"second"]];
}
else if([theObj.itemName isEqualToString:#"Main Street"]){
imageView.frame = CGRectMake(15,10,13,25);
[imageView setImage:[UIImage imageNamed:#"mainstreet"]];
}
else{
imageView.frame = CGRectMake(8,8,25,25);
[imageView setImage:[UIImage imageNamed:#"iconcustom"]];
}
NSLog(#"%#",itemName);
NSLog(#"%#",itemCategory);
}
return cell;
}
Also here is my cellForRow:
- (NSInteger)tableView:(UITableView *)popTableView numberOfRowsInSection:(NSInteger)section {
return [self.theArray count] + 1; //Add Extra cell to beginning
}
Any ideas would be greatly appreciated.
You need to use a different reuseIdentifier for your first cell. Try this:
NSString *cellIdentifier;
if (indexPath.row == 0) {
cellIdentifier = #"first";
} else {
cellIdentifier = #"not first";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
// .. cell initialization
}
Obligatory tangential answer - have you thought about setting the tableHeaderView on the UITableView instead? I think that'd accomplish what you're trying to do in a cleaner way (in that it adds an arbitrary view to the top of the table).
Just create a UIView with your "add a new item" controls in it and then set it as the header view when first creating the table.
The issue is here
static NSString *CellIdentifier = #"Cell";
static NSInteger NameTag = 1;
UITableViewCell *cell = [popTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
you are dequeueing all of the cells with the same identifier. Row 1 (index 0) needs to have its own CellIdentifier. Also it looks like you keep adding subviews to the same cells that you dequeue. On your if(cell == nil) check you may want to decide if you want to remove all of the cells contentView subviews or reuse them.

image in an Expanded TableViewCell is lost after scrolling

I am creating an application in which i have many table cells(>300). I have successfully implemented expanding and collapsing tableview cells. On expansion an image is displayed which is fetched from a webservice, on clicking the expanded cell, the cell collapses again, if another cell is clicked the previous cell collapsed and current cell expands. Now the problem is if the user scrolls the tableview with the cell expanded table works fine but when he returns
to it the image gets lost, and there is a bit of problem with the functionality as well( the table takes that cell to be collapsed).
Moreover if the user keeps on scrolling the table down he can encounter that image in a collapased cell(which looks very bad), i think its because dequeueReusableCellWithIdentifier is fetching the already expanded cell.
PS: Every image is different based on the cell value but it is fetched in a different call(not al together ie to fetch 300 images i make 300 independent calls).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UIImageView * imageView;
UILabel * nameLabel;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(45.0, 5.0, 245.0, 34.0)];
nameLabel.font = [UIFont fontWithName:CELL_FONT size:CELL_FONT_SIZE];
nameLabel.tag = 2;
nameLabel.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:nameLabel];
[nameLabel release];
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, 5.0, 30.0, 30.0)];
imageView.tag = 1;
imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:imageView];
[imageView release];
}
else {
imageView = (id)[cell.contentView viewWithTag:1];
nameLabel = (id)[cell.contentView viewWithTag:2];
}
return cell;
}