Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a custom UITableViewCell, and when it's selected, it expands and adds a UILabel to the selected cells UIView that I added in the storyBoard.

When I run the app and select a cell, the label gets added to myView as expected. The problem is, when I scroll down, the label is also shown at another cell.

Apparently the reason its behaving like so, is because I'm reusing the cell and I don't clean them. I'm trying to call the method of prepareForReuse and 'cleaning' the cell, but I'm having trouble doing that. Here is my code:

Objective-C
- (void)prepareForReuse
{
    mainVC *c = [[mainVC alloc] init];
    if (c.info) {
        [c.info removeFromSuperview];
    }
}
- (void)viewDidLoad {
    self.sortedDictionary = [[NSArray alloc] initWithObjects:@"Californa", @"Alabama", @"Chicago", @"Texas", @"Colorado", @"New York", @"Philly", @"Utah", @"Nevadah", @"Oregon", @"Pensilvainia", @"South Dekoda", @"North Dekoda", @"Iowa", @"Misouri", @"New Mexico", @"Arizona", @"etc", nil];

    self.rowSelection = -1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CategorieCell *customCell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    customCell.title.text = [self.sortedDictionary objectAtIndex:indexPath.row];
    return customCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CategorieCell *customCell = (CategorieCell *)[tableView cellForRowAtIndexPath:indexPath];

    if (self.info) {
        [self.info removeFromSuperview];
    }

    self.info = [[UILabel alloc] init];
    [self.info setText:@"Hello"];
    [self.info setBackgroundColor:[UIColor brownColor]];

    CGRect labelFrame = CGRectMake(0, 0, 50, 100);
    [self.info setFrame:labelFrame];

    [customCell.infoView addSubview:self.info];

    NSLog(@"%ld", (long)indexPath.row);

    self.rowSelection = [indexPath row];
    [tableView beginUpdates];
    [tableView endUpdates];

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath row] == self.rowSelection) {
        return 159;
    }
    return 59;
}
Posted
Updated 4-Feb-15 12:33pm
v3

1 solution

prepareForReuse is only for cleaning up internal resources, like setting images to nil. For instance the function could be implemented in your CategoryCell AND REALLY NOT in the View Controller.

What you do in allocating a view controller and using it is nonsens and dangerous. (too say it halfways politly)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900