Having trouble loading images into a grid - iphone

im having trouble loading images into a uitable view from an xml file, i have everything loading correctly, the problem is in the uitableview instead of loading the images 0-9 it loads only 0-7 then images 0 and 1 ?
attached is the project, any help would be appreciated
thanks
http://jptarry.com/iPhoneTest/iphoneGrid.zip

I hope i'm right. I don't have a mac right now to test this, but I've seen some errors in the code.
In MainViewController when you are reusing the cell, you simply return the old cell without any change.
I think this is why you get 0-7 then 0-1 again. Most probably there are 7 cells visible on the screen and when you start scrolling you are simply returning the dequeued cells (which are 0 and 1 because you are scrolling down and those cells are out of the screen).
When reusing a cell, you should reinitialize the asyncImageView with the image for the current index. I'll copy-paste some code but this is more as a guideline because i can't compile/test it:
Also, you are attaching the same tag to multiple asyncImageViews you create in the same cell. You won't be able to get all of them back. Attach ids based on the index or something.
EDIT:
This is how i got it working. However, I really don't understand the logic behing your code where you arrange the buttons in a cell.
Also, there is still an issue with AsyncImageView. While it is loading the new image, it is displaying the old one - this is why you will see that when you scroll the old images first appear with a activity indicator, then the new images appear. You should have a loading state for AsyncImageView where it displays something neutral.
Also, I'm really happy with the tagging method, but it works :)
Ok, enough talk, here's the code i changed:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
AsyncImageView *asyncImageView = nil;
int section = indexPath.section;
NSMutableArray *sectionItems = [sections objectAtIndex:section];
int n = ([sectionItems count]) ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
// Create a new cell
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int i=0;
int f=0;
while (i < [sectionItems count])
{
int yy = 4 +f*74;
//number of items per section 2
for(int j=0; j<[sectionItems count]; j++)
{
Item *item = [sectionItems objectAtIndex:j];
int buttonX = 10;
if (j != 0)
buttonX = 203;
NSLog(#"+++++++++++++++++++++++++++++++");
NSLog(#"image :: %d :: %#", j, item.image);
NSLog(#"+++++++++++++++++++++++++++++++");
CGRect frame;
frame.origin.x = buttonX;
frame.origin.y = yy;
frame.size.width = 107;
frame.size.height = 107;
asyncImageView = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImageView.backgroundColor = [UIColor clearColor];
asyncImageView.tag = ASYNC_IMAGE_TAG + f * 100 + j;
//asyncImageView.opaque = YES;
[cell.contentView addSubview:asyncImageView];
i++;
}
f = f+1;
}
}
else
{
NSLog(#"cell != nill %#", cell);
}
int i=0;
int f=0;
while (i < [sectionItems count])
{
//number of items per section 2
for(int j=0; j<[sectionItems count]; j++)
{
Item *item = [sectionItems objectAtIndex:j];
asyncImageView = (AsyncImageView *) [cell.contentView viewWithTag:ASYNC_IMAGE_TAG + f * 100 + j];
[asyncImageView loadImageFromURL:[NSURL URLWithString:item.image]];
i++;
}
f = f+1;
}
return cell;
}
EDIT2: I made a quick fix to AsyncImageView to remove the old image when loading a new one. I'll just post some code excerpts with the changes:
-(void)loadImageFromURL:(NSURL*)url {
// ADD THE FOLLOWING LINES
// Remove the old image (tagged with 1234)
[[self viewWithTag:1234] removeFromSuperview];
// END ADD
if (connection != nil) {
NSLog(#"connection != nil");
[connection cancel];
[connection release];
A little lower in the same method, where you create the image from cache, add those lines:
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// ADD THE NEXT LINE
imageView.tag = 1234; // add this line
// END ADD
[self addSubview:imageView];
And in another function, - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection where you create the new image, just add the tag again:
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// ADD THE NEXT LINE
imageView.tag = 1234;
// END ADD
[self addSubview:imageView];
imageView.frame = self.bounds;

Related

UITableView display

I add UIView in UITableviewcell. The first occurrence of all appears normal. But every time when you scroll all the strays. UILabel overlap with different values. Below is the code to create Cell. What am I doing wrong?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
float low_bound = 0;
float high_bound = 7;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
int dayStart = rndValue;
int dayMonth = 30;
int maxI = (dayStart+(7-dayStart))*(indexPath.row+1);
int Pos;
if (indexPath.row == 0) {
dayNumber = dayStart;
Pos = 0;
} else {
Pos = dayNumber;
}
for (int i=dayNumber; i < maxI; i++) {
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(4, 4, 40, 40)];
if (i > 0) {
CGRect frame = myView.frame;
frame.origin.x = (44.0*(i- Pos-1));
myView.frame = frame;
}
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(24, 0, 40, 40)];
[yourLabel setText:[NSString stringWithFormat:#"%i", i-dayStart+1]];
[myView addSubview:yourLabel];
[cell addSubview:myView];
dayNumber++;
}
return cell;
}
THe cells you are using are being reused by the system, and every tieme that happens, you just slap another label on top of all the others. You need to either remove the labels before reusing the cell by doing something like
//this needs to be placd before the for-loop
for (UIView *view in cell.contentView.subViews){
[view removeFromSuperview];
}
or you can keep references to the labels and just assign new values to them.
I would advise you to do the latter, but it will probably mean that you have to subclass UITableViewCell.
Right now, the code in your forloop keeps creating new labels and just stacks them up like a lasagna.

UIScrollView in custom table cell at cellForRowAtIndex path not working

I'm trying to implement a UIScrollView in each cell of `UITableView'. I wrote my code based on Apple's custom Scrollview project: https://developer.apple.com/library/ios/#samplecode/Scrolling/Listings/ReadMe_txt.html
Each table cell's UIScrollView scrolls through a set of labels, which are initialized in the cellForRowAtIndexPath method. Each label's text is set after initialization to equal a string from an array.
Everything works correctly until I scroll down to the 4th table cell. The UIScrollView in this cell has the same exact labels as the first cell. The same first 3 set of labels or the first 3 scrollViews keep repeating after the first 3 cells. The strange part is, when I log the label.text after it is set, the output shows the correct label.text of what should be displaying in the respective cell.
- (void)layoutScrollLabels: (float)arrayCount
{
UIView *view = nil;
NSArray *subviews = [cell.popularLinkScrollView subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UILabel class]] && view.tag >= 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
[cell.popularLinkScrollView setContentSize:CGSizeMake((arrayCount * kScrollObjWidth), [cell.popularLinkScrollView bounds].size.height)];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Custom Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dictionary = [parseDataArray objectAtIndex:indexPath.row];
NSArray *popularLinkTitleArray = [dictionary objectForKey:#"popularLinkTitleArray"];
cell.popularLinkScrollView.clipsToBounds = YES;
kScrollObjHeight = cell.popularLinkScrollView.frame.size.height;
kScrollObjWidth = cell.popularLinkScrollView.frame.size.width;
NSUInteger i;
for (i = 0; i < popularLinkTitleArray.count; i++)
{
NSString *string = [NSString stringWithFormat:#"%#", [popularLinkTitleArray objectAtIndex: i]];
UILabel *label = [[UILabel alloc] init];
label.text = [NSString stringWithFormat:#"%#", string];
label.backgroundColor = [UIColor clearColor];
label.numberOfLines = 5;
NSLog(#"%#", label.text);
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = label.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
label.frame = rect;
label.tag = i; // tag our images for later use when we place them in serial fashion
[cell.popularLinkScrollView addSubview:label];
}
[self layoutScrollLabels:popularLinkTitleArray.count];
}
return cell;
}
You should not add label as a subview to popularLinkScrollView in cellForRowAtIndexPath. If the count of labels is required to be dynamic, try this code before your for loop in cellForRowAtIndexPath.
for (UIView* subView in cell.popularLinkScrollView.subviews)
[subView removeFromSuperview];

UITableView scrolling slow, memory leak issue

I have a UITableView and a UITableCell subclass. Each table cell has two scrollviews that each rotate a dynamic amount of labels, which are created in my table cell implementation. I have poor scrolling performance and I believe it is from memory leaks. I'm referencing this stackoverflow correct answer to fix my problem: cellForRowAtIndexPath memory management.
I can't figure out how to tweak my code so I don't have to allocate memory every time I create labels.
ViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Custom Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dictionary = [parseDataArray objectAtIndex: indexPath.row];
NSArray *popularLinkTitleArray = [dictionary objectForKey:#"popularLinkTitleArray"];
NSString *soundCloudLink = [dictionary objectForKey:#"soundCloudLink"];
NSArray *soundCloudTrackTitleArray = [dictionary objectForKey:#"soundCloudTrackTitleArray"];
cell.artistNameLabel.text = artistName;
[cell createPopularLinkLabels: popularLinkTitleArray];
return cell;
}
CustomCell.m
- (void)layoutScrollLabelsForPopularLinkScrollView: (float)arrayCount
{
UIView *view = nil;
NSArray *subviews = [popularLinkScrollView subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UILabel class]] && view.tag >= 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
[popularLinkScrollView setContentSize:CGSizeMake((arrayCount * kScrollObjWidth), [popularLinkScrollView bounds].size.height)];
}
-(void) createPopularLinkLabels:(NSArray *) popularLinkTitleArray
{
popularLinkScrollView.clipsToBounds = YES;
kScrollObjHeight = popularLinkScrollView.frame.size.height;
kScrollObjWidth = popularLinkScrollView.frame.size.width;
for (UIView* subView in popularLinkScrollView.subviews)
[subView removeFromSuperview];
NSUInteger i;
for (i = 0; i < popularLinkTitleArray.count; i++)
{
NSString *string = [NSString stringWithFormat:#"%#", [popularLinkTitleArray objectAtIndex: i]];
UILabel *label = [[UILabel alloc] init];
label.text = [NSString stringWithFormat:#"%#", string];
label.backgroundColor = [UIColor clearColor];
label.numberOfLines = 5;
[label setFont:[UIFont fontWithName:#"Calibri" size:18]];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = label.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
label.frame = rect;
label.tag = i; // tag our images for later use when we place them in serial fashion
[popularLinkScrollView addSubview:label];
}
[self layoutScrollLabelsForPopularLinkScrollView:popularLinkTitleArray.count];
}
Are you using ARC? If not, you should autorelease to
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]
Cell objects are reused and you do not need to re-add subviews each time you change the contents. Just change the data and update the label frames if needed.
If you have distinctly different cells, consider using separate custom cell classes. You will need to use a separate value for the reuseIdentifier.
Also consider not creating a custom cell but just adding elements to the standard UITableViewCell. Read this about styling a cell.
The first thing you could do is try to reuse UILabels in createPopularLinkLabels. Right now, you are just removing them before adding more.
But if the number of popular links is not the same in all the cells, then you will have to remove the remaining ones or hide them and there will be no way to avoid memory allocations.
A better solution would be to insert a custom UIView inside your scroll view and draw all the texts manually instead of creating tons of subviews.
Hope this helps,
Thomas

uitableview loading the cells with previous cells' content

in my table view the cell size fits to the whole screen size. so it creating only two cells but from the 3rd cell its using old cell's content...so i am getting the incorrect data..
how 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] initWithFrame:CellFrame reuseIdentifier:CellIdentifier] autorelease];
for(UIView *v in [cell.contentView subviews])
[v removeFromSuperview];
curCellNo = indexPath.row;
if(curCellNo == 0){
min = 0;
max = 8;
x=0;
y=yForFirst;
col = 1;
}else{
if(curCellNo < prevCellNo){
min = min-12;
max = max-12;
}else{
min = max;
max = min+12;
}
x=0;
y=0;
}
prevCellNo = curCellNo;
NSLog(#"Max...%d",max);
NSLog(#"Min...%d",min);
NSLog(#"songsCount...%d",[songs count]);
for(int i=min; i<max && i<[songs count]; i++){
Song *thesong = [self.songs objectAtIndex:i];
CGRect frame;
frame.size.width=coverWidth; frame.size.height=coverHeight;
frame.origin.x=x; frame.origin.y=y;
LazyImageView* asyncImage = [[[LazyImageView alloc] initWithFrame:frame]autorelease];
NSURL* url = [NSURL URLWithString:thesong.cover];
[asyncImage loadImageFromURL:url];
UILabel *label = [[[UILabel alloc]initWithFrame:CGRectMake(x, y+artistLabelYPos, artistLabelWidth, artistLabelHeight)]autorelease];
label.text = [thesong.title stringByAppendingString:[#"\nby " stringByAppendingString:thesong.artist]];
[label setTextAlignment:UITextAlignmentLeft];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:artistLabelFontSize];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkTextColor];
label.alpha = 0.75;
UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.frame = CGRectMake(x+playBtnXPos, y+playBtnYPos, playBtnWidth, playBtnHeight);
[playBtn addTarget:self action:#selector(playBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
if(playingButton && streamer){
if(playingButtonTag == i && [streamer isPlaying]){
[playBtn setBackgroundImage:[UIImage imageNamed:pauseBtnimgName] forState:UIControlStateNormal];
playingButton = playBtn;
}else [playBtn setBackgroundImage:[UIImage imageNamed:playBtnimgName] forState:UIControlStateNormal];
}else [playBtn setBackgroundImage:[UIImage imageNamed:playBtnimgName] forState:UIControlStateNormal];
playBtn.tag = i;
[cell.contentView addSubview:asyncImage];
[cell.contentView addSubview:label];
[cell.contentView addSubview:playBtn];
label = nil;
asyncImage = nil;
if(curCellNo == 0){
y += estCoverHeight;
if(y>=(estCoverHeight*noOfRowsInCell)){
col++;
x += estCoverWidth;
if(col>=3)
y=0;
else
y=yForFirst;
}
}else{
col =3;
y += estCoverHeight;
if(y>=(estCoverHeight*noOfRowsInCell)){
x += estCoverWidth;
y=0;
}
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.contentView.transform = CGAffineTransformMakeRotation(M_PI/2);
return cell;
}
It's because you are never setting the contents of the re-used UITableViewCell's
You are only providing the conetent when (cell == nil) and a new cell is allocated
You're not clearing the contents of the cell when you reuse it. This is UITableView programming 101. Please, there are WWDC videos, Stanford videos all on iTunesU that you should be watching, tableview programming guides in text if you prefer, all that touch on cell reuse.
In a nutshell: Cells are reused to save on memory. You reuse old cells when they go off screen, allocate new ones if none can be reused. If you do reuse old cells, you have to clear any subviews you placed on them first.
On a side note, you probably want a custom cell where you do the bulk of the work you're doing in tableView:cellForRowAtIndexPath: I would strongly suggest you look into that as well.
I have made this some mistake - once you make it and fix it once, you never forget :)
Instances of UITableViewCell are cached for performance reasons. The UITableView class handles this all for you. It basically caches enough instances to cover a full screen's worth of cells plus a few. That means that a table with 100 rows will run off of the same number of instances as a table with 1000 rows.
That means it is your responsibility to update the contents as they appear.
(UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath is called when a cell is requested. In your implementation:
if(cell == nil) {
// Instantiate the UITableViewCell here
// Perform operations that need to occur on every cell, regardless of content
}
// Out here, perform content assignments
Hopefully that clears a few things up. You basically just need to shift most of the code that is inside of the conditional to outside of the conditional. That said, I'm not condoning your use of code. You really should be implementing a custom cell. It is easier than what you are doing :)
just try this
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
It worked for me.I had a UITableView with composed cells.I also faced the same problems.

Adding a row of icons to a table cell

Okay I am just totally too close to this I think. I have a tableview. In that table view everything is working except section 2 row 0.
AND -- before anyone asks...I know I am not using the *imgWordView (in the code below) and that is why the icons are not showing but i do not know where to add it to the subview so i can place it at coordinates in the cell... :)
// 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) {
if (indexPath.section == 2 && indexPath.row == 0)
{
cell = [self getCellContentViewForIconRow:CellIdentifier];
cell.backgroundColor = [UIColor grayColor];
}
else
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
}
}
The above code (except for my addition of of my section == 2 && indexPath.row == 0) is normal and generic..
getCellContentViewForIconRow is defined here:
- (UITableViewCell *) getCellContentViewForIconRow:(NSString *)cellIdentifier {
ResortsListViewController *resortsListViewController = [[ResortsListViewController alloc] init];
NSMutableArray *categoryArray = [resortsListViewController getCategoriesForLocation:[[locationData objectForKey:#"theid"]intValue]];
[resortsListViewController release];
CGRect CellFrame = CGRectMake(0, 0, 260, 60);
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CellFrame reuseIdentifier:cellIdentifier] autorelease];
cell.contentView.backgroundColor = [UIColor grayColor];
int x = 10;
int y = 10;
for (NSMutableDictionary *cat_object in categoryArray) {
CGRect Label1Frame = CGRectMake(x, y, x + 40, 40);
UILabel *lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.tag = x + 1;
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"alcohol.png"];
UIImage *imgWord = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
UIImageView *imgWordView = [[[UIImageView alloc] initWithImage:imgWord] autorelease];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
x = x + 30;
}
return cell;
}
Okay, so
ResortsListViewController *resortsListViewController = [[ResortsListViewController alloc] init];
NSMutableArray *categoryArray = [resortsListViewController getCategoriesForLocation:[[locationData objectForKey:#"theid"]intValue]];
[resortsListViewController release];
gets back a group of categories that I would use to build the filenames for the PNG images. Everything is okay so far. Then I am looping through the array to build the places for the images in the cell.
I am expecting no more than 5 images...at 30x30 each. so, to test, I just used the filename "alcohol.png" which exists. I want all 5 images to be displayed in a row inside the cell
I already do this:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 2 && indexPath.row == 0)
{
return 60;
}
}
But, all I see is my table cell (in gray like it is supposed to be) with a LONG white box inside it.
So, two questions.
1: The box (i am assuming it is the CGRect CellFrame = CGRectMake(0, 0, 260, 60);) in white. I need to know how to change that to gray...just like my cell background.
The big reason is that my icons are white...and i cannot tell if the icons are visible or not.
If the only problem is that this white CGRECT is hiding my icons, then all is well.
Otherwise we come to #2:
2: Is this the best way to put a group of icons within a cell row when the icon names are inside an array?
If not, how?
So, How do i make the CGRect gray & how do i get the 5 icons to appear horizontally in the cell?
Thanks in advance for your help!
The big long white box is your labels you are making and adding to the contentView. The UILabels are opaque with a white background. Do the following:
lblTemp.backgroundColor = [UIColor clearColor];
This will get rid of the white box so you can see what is behind your labels.
The other issue is that you you are adding your x + 40 on every iteration of your loop. I would think you would want the width to be a constant value and not adding your X coord + 40 each time, this will end up making a pretty wide set of labels across your cell.
Okay, found out how to do this elegantly and with a flair. I am voting for #bstahlhood's answer as the answer as it is partially what I needed to know..however, this subroutine in place of the one I submitted above is how I fully fixed it.
- (UITableViewCell *) getCellContentViewForIconRow:(NSString *)cellIdentifier {
ResortsListViewController *resortsListViewController = [[ResortsListViewController alloc] init];
NSMutableArray *categoryArray = [resortsListViewController getCategoriesForLocation:[[locationData objectForKey:#"theid"]intValue]];
[resortsListViewController release];
MainAppDelegate *mainAppDelegate = [[MainAppDelegate alloc] init];
CGRect CellFrame = CGRectMake(10, 10, 100, 40);
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CellFrame reuseIdentifier:cellIdentifier] autorelease];
int x = 10;
int y = 10;
int ctr = 0;
NSFileManager *fileManager = [NSFileManager defaultManager];
for (NSString *category_name in categoryArray) {
if (ctr <= 7)
{
BOOL valid_for_user = [mainAppDelegate validate_category_for_users_level:category_name];
if (valid_for_user)
{
NSMutableString *subt = [[[NSMutableString alloc]init]autorelease];
[subt appendString: category_name];
[subt appendString: #".png"];
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithString:subt]];
BOOL success = [fileManager fileExistsAtPath:filePath];
if (success)
{
UIImage *imgWord = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];
UIImageView *imgWordView = [[[UIImageView alloc] initWithImage:imgWord] autorelease];
CGRect Label1Frame = CGRectMake(x, y, 30, 30);
UILabel *lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.tag = x + 1;
// BEGIN FIX TO MY PROBLEM: thanks #bstahlhood
lblTemp.backgroundColor = [UIColor clearColor];
// END FIX TO MY PROBLEM
[lblTemp addSubview:imgWordView];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
x = x + 40;
ctr += 1;
}
}
}
}
[mainAppDelegate release];
return cell;
}
As you see I also changed the CGRECT inside my loop to fix the horizontal spacing:
CGRect Label1Frame = CGRectMake(x, y, 30, 30);
as #bstahlhood suggested. I had forgotten CGRrect commands handle the startpoints and width instead of startpoints and endpoints inside the cell area. that is why I thought I had to use x+40. As stated, it is now corrected.
I also changed this the heightForRowAtIndexPath to better balance the look of a 30x30 pixel image. The label above starts my subview 10px across and 10px down from the inside of the cell, so it just makes sense to ensure that the cell is 50px vertically and not 60px so there is exactly 10px on top and 10px on bottom of the icon.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 2 && indexPath.row == 0)
{
return 50;
}
}
So, even though I solved my own problem prior to the posting by #bstahlhood, I am giving him the vote for the correct answer as it was correct. I also wanted to point out that I wish more people would post fixed code after their issue was corrected so that others having the same issue would know what (exactly) they did. That is why I posted this code.