adding uiimageview inside cell - iphone

trying to load an image inside a cell.
i am able to load the image inside the cell but when scrolling up and down the tableView the image appears randomly inside other different cells as well...
here is some code:
- (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];
cell.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
}
if (indexPath.section == ONE_SECTION) {
switch(indexPath.row) {
case 0:{
//some code
}
break;
case 2:{
//some code
}
break;
case 3:{
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(256,0,43,43)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:imageView];
imageView.layer.cornerRadius = 10.0;
//imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.layer.masksToBounds = YES;
imageView.image = [UIImage imageNamed:#"imageName.png"];}
break;
default:
break;
}
}
if (indexPath.section == TWO_SECTION) {
//some code
}
if (indexPath.section == THREE_SECTION) {
//some code
}
return cell;
}
thank you

Try with the below code. If you are reusing cells, you dont have to add imageView repeatedly to all cells. You can create it in cell allocation part and just set imageView.image property out side it as shown below.
- (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];
cell.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(256,0,43,43)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:imageView];
imageView.layer.cornerRadius = 10.0;
//imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.layer.masksToBounds = YES;
imageView.tag = 567; //unique tag
}
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:567];
imageView.image = nil;
if (indexPath.section == ONE_SECTION) {
switch(indexPath.row) {
case 0:{
//some code
}
break;
case 2:{
//some code
}
break;
case 3:{
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:567];
imageView.image = [UIImage imageNamed:#"imageName.png"];
}
break;
default:
break;
}
}
if (indexPath.section == TWO_SECTION) {
//some code
}
if (indexPath.section == THREE_SECTION) {
//some code
}
return cell;
}
A better approach is to create custom UITableViewCell class and add UIImageView inside the init method of that cell. Then set the property as cell.imageView.image = ... in cellForRowAtIndexPath method.

Since you are using cached cells, the one that you are given may be one you added an image view to on a previous call to your code. If you assign a unique tag to your image view then, for cases where you don't want it, you can check for its presence and remove it if it's found.

Related

TableView mix up the cells

I have a TableView with Static Cells with a header which has 4 Cells, one cell in the middle carries a UIWebView and as footer a section with comments. Each comment has it's own cell.
My Problem is if the Footer has 4 or more comments, the 4th cell in the footer carries the same UIWebView as the cell in the middle.
My cellForRowAtIndexPath looks like this:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Get cell
static NSString *CellIdentifier = #"CellA";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
UITableViewCell *contentCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (contentCell == nil) {
contentCell = [[CustomDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Display
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.font = [UIFont systemFontOfSize:15];
if (item) {
// Item Info
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
// Display
switch (indexPath.section) {
case SectionHeader: {
// Header
switch (indexPath.row) {
case SectionHeaderTitle:
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
cell.textLabel.numberOfLines = 0; // Multiline
break;
case SectionHeaderDate:
cell.textLabel.text = dateString ? dateString : #"[Kein Datum]";
cell.imageView.image = nil;
break;
case SectionHeaderSharerFacebook:
cell.textLabel.text = #"Share on Facebook";
cell.imageView.image = [UIImage imageNamed:#"f_logo.png"];
break;
case SectionHeaderSharerTwitter:
cell.textLabel.text = #"Share on Twitter";
cell.imageView.image = [UIImage imageNamed:#"twitter-bird-blue-on-white.png"];
}
break;
}
case SectionDetail: {
//add webView to your cell
if (webViewDidFinishLoad == TRUE && indexPath.section != SectionComments) {
CGFloat contentHeight = webView.scrollView.contentSize.height;
webView.frame = CGRectMake(23, 10, 275, contentHeight);
} else {
webView.frame = CGRectMake(23, 10, 275, 10);
}
cell.backgroundColor = [UIColor whiteColor];
[cell addSubview:webView];
break;
}
case SectionComments: {
NSString *writerText = [[[self.commentParser.commentsArray objectAtIndex:indexPath.row] name] stringByAppendingString:#" schrieb:\n"];
writerText = [writerText stringByAppendingString:[[self.commentParser.commentsArray objectAtIndex:indexPath.row] description]];
writerText = [writerText stringByAppendingFormat:#"\n"];
cell.textLabel.text = writerText;
cell.imageView.image = nil;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0; //multiline
if (cell.textLabel.text == nil) {
cell.textLabel.text = #"Keine Kommentare vorhanden";
cell.textLabel.font = [UIFont fontWithName:#"Verdana-Italic" size:12];
}
break;
}
}
return cell;
}
}
Why is the UIWebView in the 4th cell again, and how can I change that ?
Thanks for every answer!
The reason is UITableView reuses it's cells to conserve memory. There are tons of questions on this topic, I would recommend that you read some (1, 2, ...). Briefly, when you do:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
for a cell in footer section, you get a cell which was previously in the middle section that contains a UIWebView. You need to remove the UIWebView subview before you reuse it as a cell in footer section.

UITextView text in Tableview get Overrides?

In my app i am customised the UITableView Cell with four UITextViews. Whenever i added data to the tableview and reload it. The text in the UITableViewCell get override with the previous texts.
I tried different approaches but couldn't figure out what was the problem.
I am using TableView in View Controller.
Here is the Code i used in my table View cell?
if ( [tableView isEqual:self.tableActions])
{
//Setting the text empty
static NSString *CellIdentifier = #"ActionsIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
NSLog(#"Index Path %i",[indexPath row]);
ActionDetails *actiondetails = [actionArray objectAtIndex:[indexPath row]];
NSLog(#"Action Text %#",actiondetails.actions);
//Actions
actionText=[[UITextView alloc] initWithFrame:CGRectMake(10, 5, 230,30)];
actionText.font = [UIFont systemFontOfSize:17.0];
actionText.editable = NO;
actionText.textColor=[UIColor blackColor];
actionText.text = actiondetails.actions ;
actionText.userInteractionEnabled = NO;
actionText.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:actionText];
//Owner
ownerBy=[[UITextView alloc] initWithFrame:CGRectMake(230, 5, 230,30)];
ownerBy.font = [UIFont systemFontOfSize:17.0];
ownerBy.textColor=[UIColor blackColor];
ownerBy.textAlignment = UITextAlignmentCenter;
ownerBy.text = actiondetails.owner;
ownerBy.editable = NO;
ownerBy.userInteractionEnabled = NO;
ownerBy.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:ownerBy];
}
ScreenShot
Thanks for your help guys.
Much Appreciated.
This happened to me a other day, the solution that I came up with was removing all subview from the cell after creating the cell in the if statement.
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
Remove cell identifier of Tableview otherwise take Customcell for the Tableview..
Just simple try this way :
{
//Setting the text empty
static NSString *CellIdentifier = #"ActionsIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
**// if(cell == nil) // comment this line in your code ,its work
// {**
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
**// }**
NSLog(#"Index Path %i",[indexPath row]);
ActionDetails *actiondetails = [actionArray objectAtIndex:[indexPath row]];
NSLog(#"Action Text %#",actiondetails.actions);
//Actions
actionText=[[UITextView alloc] initWithFrame:CGRectMake(10, 5, 230,30)];
actionText.font = [UIFont systemFontOfSize:17.0];
actionText.editable = NO;
actionText.textColor=[UIColor blackColor];
actionText.text = actiondetails.actions ;
actionText.userInteractionEnabled = NO;
actionText.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:actionText];
//Owner
ownerBy=[[UITextView alloc] initWithFrame:CGRectMake(230, 5, 230,30)];
ownerBy.font = [UIFont systemFontOfSize:17.0];
ownerBy.textColor=[UIColor blackColor];
ownerBy.textAlignment = UITextAlignmentCenter;
ownerBy.text = actiondetails.owner;
ownerBy.editable = NO;
ownerBy.userInteractionEnabled = NO;
ownerBy.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:ownerBy];
}
You are reusing the cell. Reused cell already has UITextview added to it.So you are overriding on it.
You must shift all your code of creating and adding UITextView to.
If(cell==nil)
{
}
After which you only need to set the Text to UITextview.
when your view did appear write reload your table view.
-(void)viewDidAppear:(BOOL)animated {
[tableView reloadData];
}
change your cellForRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// your code
}
// your code
return cell;
}
for (id vw in [[cell contentView] subviews]) {
if ([vw isKindOfClass:[UILabel class]])
{
UILabel *label = (UILabel *)vw;
[label removeFromSuperview];
}
}
for (id vw in [cell subviews]) {
if ([vw isKindOfClass:[UILabel class]])
{
UILabel *label = (UILabel *)vw;
[label removeFromSuperview];
}
}

UITableView experiences choppy scrolling when cell has a UIImageView subview

This has been driving me crazy for the better part of the day.
I've got a UITableView with UIImageViews. These imageviews load a locally saved PNG-file in the cellForRow-function of the tableview, and this works fine except the tableview will stop scrolling for a fraction of a second when a cell with an image in it scrolls into sight so to speak. I've trawled StackOverflow and google for an answer but I've come up short - so any help will be greatly appreciated.
Here is my code for the CellForRow-function:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if([currSection isEqualToString:#"composer"]){
MySlide *s = [slidesArray objectAtIndex:indexPath.row];
cell.textLabel.hidden = YES;
UIImageView *whiteView = [[UIImageView alloc] initWithFrame:CGRectMake((projectsTable.frame.size.width/2)-150, 4, 204.8, 153.6)];
if([s.slideImage isEqualToString:#""] || s.slideImage == nil){
//no custom image in this cell - go with default background image
whiteView.image = [UIImage imageNamed:#"cellback2.png"];
whiteView.backgroundColor = [UIColor whiteColor];
}else{
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
NSData *data = [[NSData alloc] initWithContentsOfFile:s.slideImage];
UIImage *im = [[UIImage alloc] initWithData:data];
whiteView.image = im;
whiteView.image = [self imageWithImage:whiteView.image CovertToSize:CGSizeMake(204.8,153.6)];
whiteView.backgroundColor = [UIColor whiteColor];
}
[cell.contentView addSubview:whiteView];
[whiteView release];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
There are a couple of changes to be made, first off the UIImageViews should be added when the cell is generated, rather than every time tableView:cellForRowAtIndexPath: is hit (as #Vishy suggests). Secondly you should cache the images you are loading from the documents directory ([UIImage imageNamed:] does this automatically for bundle resources).
#interface MyViewController () {
NSMutableDictionary *_imageCache;
}
#end
#implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
// other viewDidLoad stuff...
_imageCache = [[NSMutableDictionary alloc] init];
}
- (void)viewDidUnload {
[super viewDidUnload];
// other viewDidUnload stuff...
[_imageCache release];
_imageCache = nil;
}
- (void)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImageView *whiteView = [[UIImageView alloc] initWithFrame:CGRectMake((projectsTable.frame.size.width/2)-150, 4, 204.8, 153.6)];
whiteView.tag = 111;
whiteView.backgroundColor = [UIColor whiteColor];
[cell.contentView addSubview:whiteView];
[whiteView release];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.hidden = YES;
}
UIImageView* iView = (UIImageView*) [cell.contentView viewWithTag:111];
if([currSection isEqualToString:#"composer"]) {
MySlide *s = [slidesArray objectAtIndex:indexPath.row];
if([s.slideImage isEqualToString:#""] || s.slideImage == nil) {
//no custom image in this cell - go with default background image
iView.image = [UIImage imageNamed:#"cellback2.png"];
}
else {
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
// use the image path as the cache key
UIImage *theImage = [_imageCache objectForKey:s.slideImage];
if (theImage == nil) {
// load the image and save into the cache
theImage = [UIImage imageWithContentsOfFile:s.slideImage];
theImage = [self imageWithImage:theImage CovertToSize:CGSizeMake(204.8, 153.6)];
[_imageCache setObject:theImage forKey:s.slideImage];
}
iView.image = theImage;
}
}
}
#end
As a general rule, tableView:cellForRowAtIndexPath: is a method you need to get out of fast, so loading images from disk should be avoided wherever possible.
Change the code as per below...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImageView *whiteView = [[UIImageView alloc] initWithFrame:CGRectMake((projectsTable.frame.size.width/2)-150, 4, 204.8, 153.6)];
whiteView.tag = 111;
whiteView.backgroundColor = [UIColor whiteColor];
[cell.contentView addSubview:whiteView];
[whiteView release];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.hidden = YES;
}
UIImageView* iView = (UIImageView*) [cell.contentView viewWithTag:111];
if([currSection isEqualToString:#"composer"])
{
MySlide *s = [slidesArray objectAtIndex:indexPath.row];
if([s.slideImage isEqualToString:#""] || s.slideImage == nil)
{
//no custom image in this cell - go with default background image
iView.image = [UIImage imageNamed:#"cellback2.png"];
}
else
{
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
iView.image = [UIImage imageWithContentsOfFile:s.slideImage];
iView.image = [self imageWithImage:iView.image CovertToSize:CGSizeMake(204.8,153.6)];
}
}
}
There is also a delay the first time each UIImage is displayed. See this post for details on prompting the work at cache time rather than display time:
Setting image property of UIImageView causes major lag

UITableView scrolling and redraw issue

I know that if I have some images and subviews added in customized cell then I have to reuse the cell so that custom control won't appear on other cells but here I have other issue. I just want to have ImageView on first cell of first section so I have used IndexPath.Section==0 and IndexPath.Row==0 condition in following code but the problem is when I scroll table, the other cell will meet this condition and my code will create imageview on that cell as well. I have tried Tagging it and using same tagged cellView but it didn't help either. The cell issue is with disabling user interactions for few cells. Eventually after scrolling it disables user interactions for all cells. Is there anyway to resolve this?
Thanks.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.section == 0 && indexPath.row == 0) {
UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"me.jpg"]] autorelease];
UIView *cellView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,320,132)] autorelease];
[imageView setFrame: CGRectMake(10, 10, 54, 54)];
[cellView addSubview:imageView];
cell.backgroundView = cellView;
return cell;
} else if(indexPath.row == 0) {
NSString * title = [NSString string];
switch (indexPath.section) {
case 1:
title = #"Friends";
break;
case 2:
title = #"Accounts";
break;
case 3:
title = #"Stats";
break;
default:
title = nil;
break;
}
cell.textLabel.text = title;
cell.userInteractionEnabled = NO;
return cell;
}
cell.textLabel.text = #"Test";
return cell;
}
[RESOLVED] Correct code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.section == 0 && indexPath.row == 0) {
UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"me.jpg"]] autorelease];
cell.imageView.image = imageView.image;
cell.textLabel.text = nil;
cell.textLabel.textColor = [UIColor clearColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.userInteractionEnabled = YES;
return cell;
} else if(indexPath.row == 0) {
NSString * title = [NSString string];
switch (indexPath.section) {
case 1:
title = #"Friends";
break;
case 2:
title = #"Accounts";
break;
case 3:
title = #"Stats";
break;
default:
title = nil;
break;
}
cell.imageView.image = nil;
cell.textLabel.text = title;
cell.textLabel.textColor = [UIColor redColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.userInteractionEnabled = NO;
return cell;
}
cell.imageView.image = nil;
cell.textLabel.text = [cellItems objectAtIndex:(rows+indexPath.row-1)];
cell.textLabel.textColor = [UIColor blueColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.userInteractionEnabled = YES;
return cell;
}
[IMPROVED CODE]
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *NormalCellIdentifier = #"NormalCell";
static NSString *TitleCellIdentifier = #"TitleCell";
NSString *neededCellType;
if(indexPath.section == 0 && indexPath.row == 0) {
neededCellType = TitleCellIdentifier;
} else {
neededCellType = NormalCellIdentifier;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:neededCellType];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:neededCellType] autorelease];
//Only add content to cell if it is new
if([neededCellType isEqualToString: TitleCellIdentifier]) {
UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"me.jpg"]] autorelease];
cell.imageView.image = imageView.image;
}
}
if([neededCellType isEqualToString: NormalCellIdentifier]) {
NSString * title;
if(indexPath.row == 0) {
switch (indexPath.section) {
case 1:
title = #"Friends";
break;
case 2:
title = #"Accounts";
break;
case 3:
title = #"Stats";
break;
default:
title = nil;
break;
}
cell.textLabel.text = title;
cell.textLabel.textColor = [UIColor redColor];
cell.userInteractionEnabled = NO;
} else {
cell.userInteractionEnabled = YES;
cell.textLabel.textColor = [UIColor blueColor];
cell.textLabel.text = #"Test";
}
}
return cell;
}
I think your problem is that the reuse of cells makes it so that the cells that aren't being created as new cells have some properties set that you must redefine. For instance, try assigning cell.userInteractionEnabled = YES to all other cases and see what the result is.
The problem is that you are not allowing for the possibility that the cell that was correctly showing the image gets reused later and the image view is still in there.
Here are two solutions:
set the tag value of the image view when you create it, then when you setup the cells, include code to check for and remove the old imageView if necessary.
assign different reuse identifiers to cells that need an image view and those that do not. Then make sure that you are only adding a new image view to cells when they are being created and not when they are being reused.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *NormalCellIdentifier = #"NormalCell";
static NSString *TitleCellIdentifier = #"TitleCell";
NSString *neededCellType;
if(indexPath.section == 0 && indexPath.row == 0) {
neededCellType = TitleCellIdentifier;
} else {
neededCellType = NormalCellIdentifier;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:neededCellType];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:neededCellType] autorelease];
//Only add content to cell if it is new
if([neededCellType isEqualToString: TitleCellIdentifier]) {
UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"me.jpg"]] autorelease];
UIView *cellView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,320,132)] autorelease];
[imageView setFrame: CGRectMake(10, 10, 54, 54)];
[cellView addSubview:imageView];
cell.backgroundView = cellView;
}
}
if([neededCellType isEqualToString: NormalCellIdentifier]) {
NSString * title;
if(indexPath.row == 0) {
switch (indexPath.section) {
case 1:
title = #"Friends";
break;
case 2:
title = #"Accounts";
break;
case 3:
title = #"Stats";
break;
default:
title = nil;
break;
}
cell.textLabel.text = title;
cell.userInteractionEnabled = NO;
}
else {
cell.textLabel.text = #"Test";
return cell;
}
}
}
(Those last few lines fell out of the code box). That should do it.

Obj-C: UIImageview in Tableviewcell keep reappearing

i am working on an iphone project that shows an artwork at the top tableview section (section 0) and shows a list of items in (section 1). the tableview looks like that:
section0:
ARTWORK IMAGE
section1:
cell1: text1
cell2: text2
.
.
. and so goe like that.
but strangely the program shows another imageview at the bottom of the page when i scroll down, but it shouldnt show that image because its not section 0.
heres the code for my program :
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
switch (section) {
case 0:
return 1;
break;
case 1:
return [diskArray count];
break;
default:
return 0;
break;
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.section) {
case 0:
return 225;
break;
default:
return 44;
break;
}
}
// Customize the appearance of table view cells.
- (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];
}
// Configure the cell...
if(indexPath.section == 0)
{
if(indexPath.row == 0)
{
NSLog(#"adding image to the cell");
UIImage *img = [UIImage imageNamed:#"artwork.jpeg"];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(47, 0, 225, 225)];
imgView.image = img;
[cell addSubview:imgView];
[imgView release];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.text = nil;
}
}
else if(indexPath.section == 1){
cell.textLabel.text = [diskArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor darkGrayColor];
cell.textLabel.textColor = [UIColor whiteColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
The iPhone reuses old cells with the subview you've added. Try changing the CellIdentifier for each section.
It's because you reuse the cell, but nowhere it is reinitialized.
try this to remove the image :
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
} else {
[cell subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
//you should also reinit the other values, as textLabel, bgColor et al.
}