Chris
Chris

Reputation: 7310

UITableView dequeue not working as expected

As I scroll down the list, all the rows are there, but they keep adding more subviews the more they appear on the visible frame

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *reuse = @"RuleCell";

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuse];

if (cell == nil){
    cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:reuse];
}
NSUInteger row = indexPath.row;
[self createCell: cell onRow: row];
return cell;
}

 - (void) createCell: (UITableViewCell*)cell onRow: (NSUInteger)row
{
UIImageView* bgImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_background_spade_active.png"]];
cell.backgroundView = bgImage;
cell.textLabel.hidden = YES;

UILabel* titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(100, CGRectGetHeight(cell.frame) / 2, 200, 50)];
titleLabel.text = [[self.ruleList objectAtIndex: row] objectForKey: TitleKey];
titleLabel.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview: titleLabel];
}

Upvotes: 0

Views: 349

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31016

I think you need to execute almost all of the logic that's in createCell: only within the if (cell == nil){ segment of your code. The part that should execute where you're currently calling createCell: is just getting a reference to the titleLabel and setting its text value.

To clarify, here's the kind of modification I'm suggesting (not tested, but should give the right idea):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"RuleCell";

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuse];

    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:reuse];
        [self setUpCell: cell];
    }
    NSUInteger row = indexPath.row;
    UILabel *titleLabel = (UILabel *)[cell.contentView viewWithTag:42];
    titleLabel.text = [[self.ruleList objectAtIndex: row] objectForKey: TitleKey];
    return cell;
}

- (void) setUpCell: (UITableViewCell*)cell
{
    UIImageView* bgImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_background_spade_active.png"]];
    cell.backgroundView = bgImage;
    cell.textLabel.hidden = YES;

    UILabel* titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(100, CGRectGetHeight(cell.frame) / 2, 200, 50)];
    titleLabel.tag = 42;
    titleLabel.backgroundColor = [UIColor clearColor];
    [cell.contentView addSubview: titleLabel];
}

Upvotes: 1

Related Questions