I'm using the method that Apple shows on using subviews in table (most of what is below is from their documentation). I am only pulling in via an rss feed about 12 images, but this results in slow scrolling - if I get rid of the images it moves smoothly. The images are not big, so that can't be the problem. Before looking into more involved solutions (background processing, etc.), is there anything I can do to make this work better?
Thanks for any help you can give on this.
#define MAINLABEL_TAG 1
#define SECONDLABEL_TAG 2
#define PHOTO_TAG 3
-(UITableViewCell *)tableView : (UITableView *)tableView cellForRowAtIndexPath : (NSIndexPath *)indexPath {
UILabel * mainLabel, * secondLabel;
UIImageView * photo;
static NSString * CellIdentifier = # "Cell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(100.0, 0.0, 210.0, 0.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont systemFontOfSize:14.0];
mainLabel.textAlignment = UITextAlignmentRight;
mainLabel.textColor = [UIColor blackColor];
mainLabel.opaque = YES;
mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview : mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(90.0, 30.0, 220.0, 0.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont systemFontOfSize:12.0];
secondLabel.textAlignment = UITextAlignmentRight;
secondLabel.textColor = [UIColor darkGrayColor];
secondLabel.opaque = YES;
secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview : secondLabel];
photo = [[[UIImageView alloc] initWithFrame:CGRectMake(30.0, 3.0, 50.0, 40.0)] autorelease];
photo.tag = PHOTO_TAG;
photo.opaque = YES;
photo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview : photo];
} else {
mainLabel = (UILabel *)[cell.contentView viewWithTag : MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag : SECONDLABEL_TAG];
photo = (UIImageView *)[cell.contentView viewWithTag : PHOTO_TAG];
}
// Configure the cell.
mainLabel.text = [[items objectAtIndex:indexPath.row] objectForKey:# "title"];
secondLabel.text = [[items objectAtIndex:indexPath.row] objectForKey:# "teacher"];
NSString * path = [[items objectAtIndex:indexPath.row] objectForKey:# "audimage"];
NSString * mypath = [path stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL * url = [NSURL URLWithString:mypath];
NSData * data = [NSData dataWithContentsOfURL:url];
UIImage * img = [[UIImage alloc] initWithData:data];
photo.image = img;
return cell;
[cell release];
}
It looks like every time you're configuring a cell, you re-download the entire image from the web (or reading from the hard disk, if that's where your URL points to):
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
This is really slow! The way UITableView works is by reusing cells - every time a cell goes off-screen, it may be given back to the cellForRowAtIndexPath method to be used as the next cell that becomes visible.
This means that every time a new cell becomes visible, you're downloading and creating its image.
Instead, you have two options:
Download and store all the images first (if there are only 12, it probably won't take too much memory).
Download the images as-needed, and if you get a memory warning, dump some of the cached images. This is a bit harder to implement, so I'd try the first solution first.
Related
I am experiencing performance problems when using some subviews on my UITableViewCells. After I keep scrolling it eventually starts getting very slow.
First step I am doing is creating a common UIView for every cell, essentially this is creating a white cell with a rounded effect on the cell with a shadow. The performance for this seems to be normal so I don't think it's the culprit.
Here is the code I am using to do this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *NewsCellIdentifer = #"NewsCellIdentifier";
NewsItem *item = [self.newsArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NewsCellIdentifer];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NewsCellIdentifer];
cell.contentView.backgroundColor = [UIColor clearColor];
UIView *whiteRoundedCornerView = [[UIView alloc] initWithFrame:CGRectMake(10,10,300,100)];
whiteRoundedCornerView.backgroundColor = [UIColor whiteColor];
whiteRoundedCornerView.layer.masksToBounds = NO;
whiteRoundedCornerView.layer.cornerRadius = 3.0;
whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(-1, 1);
whiteRoundedCornerView.layer.shadowOpacity = 0.5;
[cell.contentView addSubview:whiteRoundedCornerView];
[cell.contentView sendSubviewToBack:whiteRoundedCornerView];
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
cell.layer.opaque = YES;
cell.opaque = YES;
}
[cell.contentView addSubview:[self NewsItemThumbnailView:item]];
return cell;
}
Here is the method that returns the thumbnail view of the graphic and text:
- (UIView *) NewsItemThumbnailView:(NewsItem *)item
{
UIView *thumbNailMainView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 50, 70)];
UIImageView *thumbNail = [[UIImageView alloc] initWithImage:[UIImage imageNamed:item.ThumbNailFileName]];
thumbNail.frame = CGRectMake(10,10, 45, 45);
UILabel *date = [[UILabel alloc] init];
date.frame = CGRectMake(10, 53, 45, 12);
date.text = item.ShortDateString;
date.textAlignment = NSTextAlignmentCenter;
date.textColor = [BVColors WebDarkGrey];
CGFloat fontSize = 10.0;
date.font = [BVFont Museo:&fontSize];
date.opaque = YES;
thumbNail.opaque = YES;
thumbNailMainView.opaque = YES;
[thumbNailMainView addSubview:thumbNail];
[thumbNailMainView addSubview:date];
return thumbNailMainView;
}
The performance problem seems to be when I add the thumbnail view to the cell because when I comment that line out, I don't seem to have it. The thumbnail information is dynamic and will change with each cell. I would appreciate any advice on how I should do this without degrading the performance.
UITableView will call tableView:cellForRowAtIndexPath: each time a cell comes into view, and dequeueReusableCellWithIdentifier: will reuse existing cell objects if they are available. These two facts combine to put you in a scenario where every time you scroll, the same finite number of cell objects end up with an increasing number of subviews.
The proper approach is to create a custom UITableViewCell subclass that has a property for thumbnailView. In the setter for that property, remove the previous thumbnail (if any) and then add the new one to the contentView. This ensures that you'll only ever have one thumbnail subview at any time.
A less optimal approach would be adding a tag to the UIView returned from NewsItemThumbnailView (thumbNailMainView.tag = someIntegerConstant) and then searching for any view with that tag and removing it before adding another:
// remove old view
UIView *oldThumbnailView = [cell.contentView viewWithTag:someIntegerConstant];
[oldThumbnailView removeFromSuperview];
// add new view
[cell.contentView addSubview:[self NewsItemThumbnailView:item]];
I ended up leveraging a solution found on this stackoverflow post:
How should I addSubview to cell.contentView?
Essentially when the cell is first initialized I am setting the view as mentioned by Nishant; however once the cell is reused I am extracting out the items I need to change, such as an UIImageView and then a UILabel. Since these are pointers I can modify just what I need when I need to and the performance is fast again. Here is a abbreviated version of what I did.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *NewsCellIdentifer = #"NewsCellIdentifier";
NewsItem *item = [self.newsArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NewsCellIdentifer];
UIView *thumbNailMainView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 50, 70)];
UIImageView *thumbNail;
UIView *textMainView = [[UIView alloc] initWithFrame:CGRectMake(20,20,80,80)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(52,-5, 70, 20)];
UILabel *teaserLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,20, 210, 40)];
UIView *newsItemCornerMainView = [[UIView alloc] initWithFrame:CGRectMake(255.7, 55.2, 55, 55)];
UIImageView *cornerIconView;
// If the cell doesn't existing go ahead and make it fresh.
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NewsCellIdentifer];
// Configure all the various subviews
..... //Sample below
// Make the title view
headerLabel.text = item.Title;
CGFloat textfontSize = 16.0f;
headerLabel.font = [BVFont Museo:&textfontSize];
headerLabel.textColor = [BVColors WebBlue];
headerLabel.textAlignment = NSTextAlignmentLeft;
headerLabel.numberOfLines = 0;
headerLabel.tag = 50;
// Make the Teaser view
teaserLabel.text = item.Teaser;
teaserLabel.numberOfLines = 0;
CGFloat tfontSize = 13.0f;
teaserLabel.textAlignment = NSTextAlignmentLeft;
teaserLabel.textColor = [BVColors WebDarkGrey];
teaserLabel.font = [BVFont HelveticaNeue:&tfontSize];
[teaserLabel sizeToFit];
teaserLabel.tag = 51;
[textMainView addSubview:headerLabel];
[textMainView sendSubviewToBack:headerLabel];
[textMainView addSubview:teaserLabel];
[cell.contentView addSubview:textMainView];
....
}
thumbNail = (UIImageView *) [cell viewWithTag:47];
[thumbNail setImage:[UIImage imageNamed:item.ThumbNailFileName]];
headerLabel = (UILabel *) [cell viewWithTag:50];
headerLabel.text = item.Title;
teaserLabel = (UILabel *) [cell viewWithTag:51];
teaserLabel.text = item.Teaser;
cornerIconView = (UIImageView *) [cell viewWithTag:48];
[cornerIconView setImage:[UIImage imageNamed:item.CornerIconFileName]];
return cell;
}
You should change thumbNailMainView content only everytime but you should not add its content on cell everytime.
So add this line where you are allocating cell
[cell.contentView addSubview:[self NewsItemThumbnailView:item]];
add this inside braces. and then access thumbNailMainView from cell and pass that item data which you need to change for each cell.
Assign a tag to thumbNailMainView and its subview thumbNail then access it as
UIView *_thumbNailMainView = [cell.contentView viewWithTag:_thumbNailMainView_tag];
UIImageView *_thumbNail = [_thumbNailMainView viewWithTag:thumbNail_tag];
_thumbNail.image = [UIImage imageNamed:item.ThumbNailFileName];
Hope it helps you.
I am using NSOperationQueue for caching images in background.
Here is the code below:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"CellIdentifier";
UITableViewCell *cell;
cell = [self.mUpcomEventsTable dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImageView *imgView;
UILabel *lblEventName;
UILabel *lblDate;
UILabel *lblTime;
if(self.mEventNameArr != NULL)
{
NSString *imageUrlString = [NSString stringWithFormat:#"%#", [self.mEventImageArr objectAtIndex:indexPath.row]];
UIImage *cachedImage = [self.imageCache objectForKey:imageUrlString];
NSLog(#"cache:%#", self.imageCache);
imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 90)];
lblEventName = [[UILabel alloc]initWithFrame:CGRectMake(90, 10, 200, 30)];
lblEventName.text = [self.mEventNameArr objectAtIndex: indexPath.row];
lblEventName.font = [UIFont fontWithName:#"Helvetica-Bold" size:18];
lblDate = [[UILabel alloc]initWithFrame:CGRectMake(90, 50, 100, 30)];
lblDate.text = [self.mEventDateArr objectAtIndex:indexPath.row];
lblTime = [[UILabel alloc]initWithFrame:CGRectMake(190, 50, 100, 30)];
lblTime.text = [self.mEventTimeArr objectAtIndex:indexPath.row];
strEventName = lblEventName.text;
strEventDate = lblDate.text;
strEventTime = lblTime.text;
if (cachedImage)
{
imgView.image = cachedImage;
}
else
{
// you'll want to initialize the image with some blank image as a placeholder
imgView.image = [UIImage imageNamed:#"Placeholder.png"];
// now download in the image in the background
NSLog(#"queue:%#",self.imageDownloadingQueue);
[self.imageDownloadingQueue addOperationWithBlock:^{
NSURL *imageUrl = [NSURL URLWithString:imageUrlString];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = nil;
if (imageData)
image = [UIImage imageWithData:imageData];
if (image)
{
[self.imageCache setObject:image forKey:imageUrlString];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UITableViewCell *updateCell = [tableView cellForRowAtIndexPath:indexPath];
if (updateCell)
imgView.image = cachedImage;
}];
}
}];
}
}
else cell.textLabel.text = #"No event";
[cell addSubview:imgView];
[cell addSubview:lblEventName];
[cell addSubview:lblDate];
[cell addSubview:lblTime];
return cell;
}
It is not going in this line
[self.imageDownloadingQueue addOperationWithBlock:^{
it go outside from this. Why so, please help for above.
Took idea from here link.
There are a lot of disadvantage of using NSOperationQueue. One of them is your image will flick when every time you scroll the UITableView.
I'd suggest you to use this AsyncImageView. I've used it and it work wonders. To call this API:
ASyncImage *img_EventImag = alloc with frame;
NSURL *url = yourPhotoPath;
[img_EventImage loadImageFromURL:photoPath];
[self.view addSubView:img_EventImage]; // In your case you'll add in your TableViewCell.
It's same as using UIImageView. Easy and it does most of the things for you. AsyncImageView includes both a simple category on UIImageView for loading and displaying images asynchronously on iOS so that they do not lock up the UI, and a UIImageView subclass for more advanced features. AsyncImageView works with URLs so it can be used with either local or remote files.
Loaded/downloaded images are cached in memory and are automatically cleaned up in the event of a memory warning. The AsyncImageView operates independently of the UIImage cache, but by default any images located in the root of the application bundle will be stored in the UIImage cache instead, avoiding any duplication of cached images.
The library can also be used to load and cache images independently of a UIImageView as it provides direct access to the underlying loading and caching classes.
guys, I have UITableView with some images, which are loading from internet. Images is very little, but my tableview isn't work perfect.
My code:
static NSString *CellIdentifier = #"Cell";
TDBadgedCell *cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.badgeColor = [UIColor colorWithRed:((float)128 / 255.0f) green:((float)161 / 255.0f) blue:((float)176 / 255.0f) alpha:1];
NSDictionary *dict = nil;
if (searching == NO) {
dict = [companies objectAtIndex:indexPath.row];
} else {
dict = [copyListOfItems objectAtIndex:indexPath.row];
}
cell.badgeString = [NSString stringWithFormat:#"%#",[dict objectForKey:#"rating"]];
cell.textLabel.numberOfLines = 2;
cell.textLabel.text = [dict objectForKey:#"title"];
cell.textLabel.textColor = [UIColor colorWithRed:((float)80 / 255.0f) green:((float)80 / 255.0f) blue:((float)80 / 255.0f) alpha:1];
cell.textLabel.font = [UIFont fontWithName:#"Verdana" size:17.0];
UIImage *img = [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dict objectForKey:#"image"]]]] scaleToFitSize:CGSizeMake(16, 16)];
cell.imageView.image = img;
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
TDBadgedCell can't be reason, because without images it works perfect.
I'm using open sourse classes to resize UIImage. You can found it here.
Have you any ideas?
You could do the image downloading part in another thread so it won't block the main. You can do this like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
// download the images here
dispatch_async(dispatch_get_main_queue(), ^{
// add them to your cell here
});
});
So you need to switch to another thread for downloading and then get back to the main thread and add them to the UI. UI elements must only be handled with in the main thread.
I have posted code that shows you to deal with this. We have a class MyImageDownloader that downloads an image on request and posts a notification when it arrives:
https://github.com/mattneub/Programming-iOS-4-Book-Examples/blob/master/p754p772downloader/p754downloader/MyImageDownloader.m
The table view data source supplies a placeholder if a MyImageDownloader has no image, and supplies the image if it has one:
https://github.com/mattneub/Programming-iOS-4-Book-Examples/blob/master/p754p772downloader/p754downloader/RootViewController.m
Thus, all we have to do is reload the table when an image arrives. m.
So I have some issues with my tableview. I have a custom label that I put into a tableview cell to add a little better graphics than the standard UItableviewcell. However, I was running into my first problem,
the text labels that I had on the cells were changing with and over writing each other upon scrolling, only when the cells had moved off screen and then came back. Upon some research I found that maybe it had something to do with dequeueReusableCellWithIdentifier: so I adjusted my code. this is where problem two comes in.
When I load the table everything is in its right place, correct looking and all. However when I start to scroll down I can get to all of my cells except the last one, it will go to the very bottom of the 8th cell and freeze, but I should have 9 cells loaded.
I am quite confused by some of this, could anyone provide some code or guidance to help me along?
Thanks.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Run");
CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *keys = [[appDelegate rowersDataStore] allKeys];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure the cell...
label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 15, cell.bounds.size.width - 10, 30)] autorelease];
label.font = [UIFont boldSystemFontOfSize:16];
label.backgroundColor = [UIColor clearColor];
label.shadowColor = [UIColor colorWithWhite:1.0 alpha:0.5];
label.shadowOffset = CGSizeMake(0,1);
label.textColor = [UIColor colorWithRed:0x4c/255.0 green:0x4e/255.0 blue:0x48/255.0 alpha:1.0];
switch (indexPath.section) {
case 0:
label.frame = CGRectMake(0, 15, cell.bounds.size.width - 10, 30);
label.textAlignment = UITextAlignmentCenter;
break;
case 1:
label.textAlignment = UITextAlignmentLeft;
UIImage *accessoryImage = [UIImage imageNamed:#"content_arrow.png"];
UIImageView *accessoryView = [[UIImageView alloc] initWithImage:accessoryImage];
cell.accessoryView = accessoryView;
[accessoryView release];
break;
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
UIImage* img = [UIImage imageNamed:#"odd_slice.png"];
imgView.image = img;
cell.backgroundView = imgView;
[imgView release];
//Selected State
UIImage *selectionBackground = [UIImage imageNamed:#"row_selected.png"];
UIImageView *selectionView = [[UIImageView alloc] initWithFrame:cell.frame];
selectionView.image = selectionBackground;
cell.selectedBackgroundView = selectionView;
[selectionView release];
}
switch (indexPath.section) {
case 0:
[label setText:#"Click to add new rower"];
break;
case 1:
[label setText:[[[appDelegate rowersDataStore] objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:#"Name"]];
break;
}
//Adds Text
[cell addSubview:label];
return cell;
}
I see several issues here. First, the general structure of this method should be...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
// Attempt to dequeue the cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// If cell does not exist, create it, otherwise customize existing cell for this row
if (cell == nil) {
// Create cell
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure cell:
// *** This section should configure the cell to a state independent of
// whatever row or section the cell is in, since it is only executed
// once when the cell is first created.
}
// Customize cell:
// *** This section should customize the cell depending on what row or section
// is passed in indexPath, since this is executed every time this delegate method
// is called.
return cell;
}
Basically, UITableView uses a single UITableViewCell instance to draw every cell in the table view. So, when you first create this cell, you should configure it to a state that is common to all cells that will use this instance, independent of whatever row or section is passed in indexPath. In your example, this involves creating the label, image, and background image instances and adding them as subviews to the cell.
Once the cell is created (aka outside the if (cell == nil) statement), you should customize its properties according to how the cell should look for the specific row and section contained in indexPath. Since you want to access your custom label in this part of the code, I assigned a tag value to it so that we can access it beyond the code segment where it was created using viewWithTag:. Once we have the label, we can customize it according to the section as well as do anything else we want, such as customize the accessory view.
I slightly modified/cleaned up your code below. This is by far not the most efficient or elegant way to do what you want to do, but I was trying to keep as much of your code as possible. I haven't tested this, but if you try it it should work:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Run");
CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *keys = [[appDelegate rowersDataStore] allKeys];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure the cell...
UILabel *label;
label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 15, cell.bounds.size.width - 10, 30)] autorelease];
label.font = [UIFont boldSystemFontOfSize:16];
label.opaque = NO;
label.backgroundColor = [UIColor clearColor];
label.shadowColor = [UIColor colorWithWhite:1.0 alpha:0.5];
label.shadowOffset = CGSizeMake(0,1);
label.textColor = [UIColor colorWithRed:0x4c/255.0 green:0x4e/255.0 blue:0x48/255.0 alpha:1.0];
label.tag = 100;
[cell addSubview:label];
[label release];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
UIImage* img = [UIImage imageNamed:#"odd_slice.png"];
imgView.image = img;
cell.backgroundView = imgView;
[imgView release];
//Selected State
UIImage *selectionBackground = [UIImage imageNamed:#"row_selected.png"];
UIImageView *selectionView = [[UIImageView alloc] initWithFrame:cell.frame];
selectionView.image = selectionBackground;
cell.selectedBackgroundView = selectionView;
[selectionView release];
}
UILabel *lbl = (UILabel *)[cell viewWithTag:100];
switch (indexPath.section) {
case 0:
cell.accessoryView = nil;
lbl.frame = CGRectMake(0, 15, cell.bounds.size.width - 10, 30);
lbl.textAlignment = UITextAlignmentCenter;
[label setText:#"Click to add new rower"];
break;
case 1:
UIImage *accessoryImage = [UIImage imageNamed:#"content_arrow.png"];
UIImageView *accessoryView = [[UIImageView alloc] initWithImage:accessoryImage];
cell.accessoryView = accessoryView;
[accessoryView release];
lbl.frame = CGRectMake(20, 15, cell.bounds.size.width - 10, 30);
lbl.textAlignment = UITextAlignmentLeft;
[lbl setText:[[[appDelegate rowersDataStore] objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:#"Name"]];
break;
}
return cell;
}
I am wanting to add a custom background and selected background images for my tableview cells. Currently it seems that when the cells get reused, the background images get screwed up, the top cell will use the bottom cells image, etc etc.
Am I reusing cells incorrectly in this case?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UIImageView *linkAvailableImageView = nil;
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)];
UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)];
UIImageView *backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, tableView.bounds.size.width-20, 44)];
UIImageView *selectedBackgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, tableView.bounds.size.width-20, 44)];
// Asset
Asset *asset = nil;
asset = (Asset *)[items objectAtIndex:indexPath.row];
int count = [items count];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if (indexPath.row == 0 && count > 1) {
backgroundImage.frame = CGRectMake(10, 0, tableView.bounds.size.width-20, 45);
backgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundTop.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:10];
selectedBackgroundImage.frame = CGRectMake(10, -1, tableView.bounds.size.width-20, 45);
selectedBackgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundSelectedTop.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:10];
} else if (indexPath.row == count-1 && count > 1) {
backgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundBottom.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:10];
selectedBackgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundSelectedBottom.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:10];
} else if (indexPath.row == 0 && count == 1) {
backgroundImage.frame = CGRectMake(10, -1, tableView.bounds.size.width-20, 45);
backgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundSingle.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:10];
selectedBackgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundSelectedSingle.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:10];
} else {
backgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundMiddle.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:10];
selectedBackgroundImage.image = [[UIImage imageNamed:#"MDACCellBackgroundSelectedMiddle.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:10];
}//end
backgroundImage.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[backgroundView addSubview:backgroundImage];
[backgroundImage release];
selectedBackgroundImage.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[selectedBackgroundView addSubview:selectedBackgroundImage];
[selectedBackgroundImage release];
cell.backgroundView = backgroundView;
[backgroundView release];
cell.selectedBackgroundView = selectedBackgroundView;
[selectedBackgroundView release];
linkAvailableImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.bounds.size.width-39, 9, 24, 24)] autorelease];
linkAvailableImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
linkAvailableImageView.image = [UIImage imageNamed:#"MDACLinkArrow.png"];
linkAvailableImageView.tag = 3;
[cell.contentView addSubview:linkAvailableImageView];
} else {
linkAvailableImageView = (UIImageView *)[cell.contentView viewWithTag:3];
}
// Get asset
cell.textLabel.opaque = NO;
cell.textLabel.text = asset.name;
cell.textLabel.font = [UIFont boldSystemFontOfSize:17];
cell.textLabel.backgroundColor = [UIColor colorWithWhite:94./255. alpha:1];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.shadowColor = [UIColor colorWithWhite:0 alpha:0.6];
cell.textLabel.shadowOffset = CGSizeMake(0, -1);
// Set the kind of disclosure indicator
if ([asset.children intValue] > 0) {
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}//end
// Lazy Load the image
if (!asset.appIcon) {
// Download icon
[self startIconDownload:asset forIndexPath:indexPath];
// if a download is deferred or in progress, return a placeholder image
cell.imageView.image = [UIImage imageNamed:#"default-icon.png"];
} else {
cell.imageView.image = asset.appIcon;
}//end
return cell;
}//end
The problem here is that you are using the same cell identifier regardless of the position in the table view.
So you initially create the cells based on the indexPath.row and the count, but you associate those cells with an identifier of #"Cell". So when you scroll down dequeueReusableCellWithIdentifier will return a cell configured for the beginning of the list (indexPath.row == 0 && count > 1) and use it for the end of the list.
You need to make sure cell identifier reflects the code at the beginning of your cell==nill if block, so that you only reuse cells that have been configured for the position in the table you are creating.
As Eiko points out, you are also leaking your UIView and UIImageView objects. You could stick them in the if block, release them explicitly or just make them autorelease.
Sorry, but that code has lots of problems: You are leaking the UIView and UIImageView objects, and the whole reuse of cells is wrong, hence your problems.
You should set up a new cell (with views) only in the if (cell == nil) part, and don't forget to release/autorelease your views. Then, outside of that block, you configure your cell accordingly (set its contents).
I strongly suggest to look through some of Apple's example projects!