0

当我向下滚动列表时,所有行都在那里,但它们会不断添加更多子视图,它们出现在可见框架上的次数越多

- (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];
}
4

1 回答 1

1

我认为您需要执行createCell:仅在if (cell == nil){代码段中的几乎所有逻辑。应该在您当前调用createCell:的地方执行的部分只是获取对的引用titleLabel并设置其文本值。

为了澄清,这是我建议的修改类型(未经测试,但应该给出正确的想法):

- (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];
}
于 2012-10-07T16:13:47.483 回答