views:

110

answers:

3

Hey all, I am trying to add custom labels to my cell in UITableView. When I try to do this the display is messed up and I am unable to figure out what exactly is going on. Please find the image below and I will post the method I wrote..

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    //cell.textLabel.font=[UIFont systemFontOfSize:16];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSString *contact=[contactKeys objectAtIndex:[indexPath section]];
    NSArray *contactSection=[contactNames objectForKey:contact];
    NSMutableArray *sugar=[db sugarId];

    if (isSearchOn) { 
        NSString *cellValue = [searchResult objectAtIndex:indexPath.row]; 
        NSArray *splitText = [cellValue componentsSeparatedByString:@":"];
        NSString *contactText = [NSString stringWithFormat:@"%@ %@", [splitText objectAtIndex:1], [splitText objectAtIndex:0]];
        //NSString *result=[contactText stringByAppendingString:[sugar objectAtIndex:[indexPath row]]];
        firstLabel=[[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 40)]autorelease];                                                  
        firstLabel.tag =40; //This should be a constant probably
        firstLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
        firstLabel.text = contactText;
        [firstLabel sizeToFit];
        [cell.contentView addSubview:firstLabel];

        sugarLabel = [[UILabel alloc] initWithFrame:
                      CGRectMake(10+firstLabel.frame.size.width+2, 10, 300, 60)];
        sugarLabel.tag =40; //This should be a constant probably
        //sugarLabel.font = [UIFont boldSystemFontOfSize:16];
        sugarLabel.text = [sugar objectAtIndex:[indexPath row]];
        [sugarLabel setHidden:YES];        
        [cell.contentView addSubview:sugarLabel];


        cell.textLabel.text =firstLabel.text;
        } else {
         NSString *cellText = [contactSection objectAtIndex:[indexPath row]];

            // split the text by the : to get an array containing { "AAA", "BBB" }
            NSArray *splitText = [cellText componentsSeparatedByString:@":"];

            // form a new string of the form "BBB AAA" by using the individual entries in the array
            NSString *contactText = [NSString stringWithFormat:@"%@ %@", [splitText objectAtIndex:1], [splitText objectAtIndex:0]];

            firstLabel=[[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 40)]autorelease];                                                  
            firstLabel.tag =40; //This should be a constant probably
            //firstLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
            firstLabel.text = contactText;
            [firstLabel sizeToFit];
            [cell.contentView addSubview:firstLabel];

            sugarLabel = [[UILabel alloc] initWithFrame:
                                    CGRectMake(10+firstLabel.frame.size.width+2, 10, 300, 60)];
            sugarLabel.tag =40; //This should be a constant probably
            //sugarLabel.font = [UIFont boldSystemFontOfSize:16];
            sugarLabel.text = [sugar objectAtIndex:[indexPath row]];
            [sugarLabel setHidden:YES];        
            [cell.contentView addSubview:sugarLabel];

            NSString *result=[NSString stringWithFormat:@"%@ %@",firstLabel.text,sugarLabel.text];
            cell.textLabel.text=result;

    }

alt text

Figure 2: This is modification to the code as suggested by BP. The result is here under.. alt text

EDIT:

Whenever I try to write stringWithFormat or the above statement, the memory is not freed and the labels are getting overlap over one other. Is there a way to solve this problem..please help me..I spent more than half a day trying to figure this but no luck

+2  A: 

If you want to have custom cells, I recommend you subclass UITableViewCell. In the example code you have given, you are creating a new label every single time the tableview asks for the cell for a row at an index path. While you are autoreleasing them, you are also adding them the the contentview of the cell, which increases their retain count and ensures that their lifetime is as long as the tableview's.

As cells are reused, you will continue to add more and more labels to it's content view, until you eventually run out of memory.

As far as the strange text output, it looks like you are adding a UILabel to one of your string with format calls.

If you were to do something like the code below, you would see something similar.

UILabel *label = [[UILabel alloc] init];
NSLog(@"%@", label);
[label release];

Edit: Seeing your edited screenshot, I'm assuming you scrolled down to the 'S' section. In which case, you are seeing the labels on top of other labels. Like I mentioned, you are creating a new label every time and putting it on top of the label you created the first (and second, third, etc) time you used the cell.

Jerry Jones
thanks for the reply Jerry..if you won't mind can you please help me how to solve this problem of readding the labels..I am a newbie to this programming..I am learning now..so any input from you will be greatly helpful.
racharambola
I almost always subclass UITableViewCell for custom cells, but that a look at this article from apple (http://developer.apple.com/iphone/library/documentation/userexperience/conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7-SW15).It has great sample code for adding subviews to UITableViewCell in a manner very similar to the way you are doing it now. They add a custom label when instantiating a cell, and give it a tag. They then use this tag to get the label for reuse.
Jerry Jones
+2  A: 

The reason you are getting the UILabel:... items showing up is the last line of the method, where you set the cell.textLabel.text. You don't want to do this if you are creating the cell with your own fields inside it.

BP
thanks for the reply BP..It worked to some extent but the values in the cells are overlapping and the appearance is not good..Please check the figure 2..
racharambola
I updated the bug under EDIT..please help me
racharambola
If you hard code a value of 200 instead of calculating an x value based on the firstLabel frame size width, does the view move over? I am just wondering if somehow that frame size width is not correct. You might want to step through the code and watch what happens with the firstLabel frame, especially before and after the sizeToFit call.
BP
Thanks for the reply BP..yup it works fine..the problem is with the stringWithFormat..The memory is autoreleased but the objects are not freed from the autorelease pool and as a result whenever I add the labels to the content view the labels get stacked on one other..If I wont add the label to the content view and assign the text to the cell label it works perfectly fine but I want to add the labels to content view so that I can access these labels later with a tag..please help..I am not finding a way to come out of it..
racharambola
hey BP I solved the problem..I referred to the link given by Jerry Jones.Thank you for your replies..
racharambola
+2  A: 
NSString *result=[NSString stringWithFormat:@"%@ %@",contactText,sugarLabel]

should read:

NSString *result=[NSString stringWithFormat:@"%@ %@",contactText,sugarLabel.text]

You are passing in an UILabel and not a NSString

edit

Try to instantiate and add UILabels only in the if (cell == nil) { block.

while accessing labels properties and writing to it outside this block is ok

vikingosegundo
please see the edited method and updated screenshot..I want sugarLabel to be hidden..i.e. its values should not be displayed on the table cell..will setHidden property works?? please help
racharambola
Please refer to screenshot 1
racharambola
So you should not add sugarLabel.text to a string, that will be displayed in another label
vikingosegundo
yup I did that viking..thanks for helping me..but somehow I am adding label one after another..I just updated the screenshot to figure 2
racharambola
I tried to do this but some cells are not being displayed on the table..I am seeing an empty cell..if (cell == nil) { firstLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 40)]; sugarLabel = [[UILabel alloc] initWithFrame: CGRectMake(10+firstLabel.frame.size.width+2, 10, 300, 60)]; cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; }
racharambola
I updated the bug under EDIT..please help me
racharambola
yup finally I am done with that..I referred to link suggested by Jerry..thanks a lot for all your replies
racharambola
hey viking I posted a question regarding cell reuse..please help me buddy..I am very bad dealing with this situation
racharambola