为什么我的UITableViewCells会重复?

时间:2010-11-30 03:34:26

标签: iphone cocoa-touch uitableview

当我在屏幕外滚动时,我会得到一些重复的细胞。我该如何解决这个问题?

// 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) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = [NSString stringWithFormat:@"Bar Cafe",indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester",indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester Shoes",indexPath.row];
            break;
        case 3:
            cell.textLabel.text = [NSString stringWithFormat:@"Local Advice - Paulina",indexPath.row];
            break;
        case 4:
            cell.textLabel.text = [NSString stringWithFormat:@"Museum Brileyeglass",indexPath.row];
            break;
        case 5:
            cell.textLabel.text = [NSString stringWithFormat:@"Redlight Swans",indexPath.row];
            break;
        case 6:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Flying Dutchman",indexPath.row];
            break;
        case 7:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Tiani Hempshop",indexPath.row];
            break;

        default:
            break;
    }

    // Configure the cell...
    //cell.textLabel.text = [NSString stringWithFormat:@"Featured Event %d",indexPath.row];
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Description %d", indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

3 个答案:

答案 0 :(得分:0)

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}

这是numberOfRowsInSection方法的正确实现,如果返回超过8,则重复行的问题开始。

答案 1 :(得分:-1)

因为在cellForRowAtIndexPath方法中,单元格被重用,每当你滚动时,索引路径将从0开始。更多细节你可以使用NSLog(@“Index Path.row =%d”,indexPath.row)和请参阅控制台窗口。

答案 2 :(得分:-1)

你的代码对我来说很好......没有prb al al ..

我想你想在每一行打印indexPath.row ..如果是这样,你必须改变如下..

[NSString stringWithFormat:@"Reefer Tiani Hempshop %d",indexPath.row];

尽管numberOfRowsInSection:返回超过8,但没有机会获得声誉。