UITableView дает странные результаты - PullRequest
0 голосов
/ 28 июля 2010

Я уверен, что это будет одна из тех вещей, когда кто-то указывает на что-то действительно очевидное, что я делаю, но я не могу ради жизни найти проблему. В основном у меня есть массив строк, и я загружаю текст из массива в свои uitableviewcells, как и когда это необходимо. Проблема возникает, когда я начинаю прокручивать и по какой-то причине ячейка № 6, т. Е. В 7-й ячейке отображается текст из позиции массива 0 поверх текста из позиции массива 6, а когда я прокручиваю вверх, текст в ячейке 0 отстает или под (я не могу точно сказать) текст из позиции массива 6 !! ?? Я понятия не имею, как я это делаю. Вот мой код:

    NSMutableArray *titles1 = [[NSMutableArray alloc]initWithCapacity:10];
[titles1 insertObject:[NSString stringWithFormat:@"0"] atIndex:0];
[titles1 insertObject:[NSString stringWithFormat:@"1"] atIndex:1];
[titles1 insertObject:[NSString stringWithFormat:@"2"] atIndex:2];
[titles1 insertObject:[NSString stringWithFormat:@"3"] atIndex:3];
[titles1 insertObject:[NSString stringWithFormat:@"4"] atIndex:4];
[titles1 insertObject:[NSString stringWithFormat:@"5"] atIndex:5];
[titles1 insertObject:[NSString stringWithFormat:@"6"] atIndex:6];
[titles1 insertObject:[NSString stringWithFormat:@"7"] atIndex:7];
[titles1 insertObject:[NSString stringWithFormat:@"8"] atIndex:8];
[titles1 insertObject:[NSString stringWithFormat:@"9"] atIndex:9];

self.secretTitles = titles1;
[titles1 release];

// Настройка внешнего вида ячеек табличного представления.

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.adjustsFontSizeToFitWidth = YES;
    }

    // Configure the cell.
    cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}


-(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    secretName = [[UILabel alloc]initWithFrame:(CGRectMake(10, 8, 100, 30))];
    secretName.backgroundColor = [UIColor clearColor];
    secretName.textColor = [UIColor whiteColor];
    secretName.font = [UIFont boldSystemFontOfSize:18];
    secretName.shadowColor = [UIColor colorWithRed:0./255 green:0./255 blue:0./255. alpha:0.7];
    secretName.shadowOffset = CGSizeMake(0, 2.0);
    secretName.text = @"";
    NSLog(@"row = %d", indexPath.row);
    secretName.text = [self.secretTitles objectAtIndex:indexPath.row];
    [cell.contentView addSubview:secretName];
}

Может кто-нибудь, пожалуйста, избавь меня от моих страданий. Большое спасибо

Jules

Ответы [ 4 ]

3 голосов
/ 28 июля 2010

Каждый раз, когда вы настраиваете ячейку, вы добавляете метку в качестве подпредставления. Но ячейка может быть повторно использована и была настроена ранее. Вам следует либо использовать существующие метки, такие как textLabel и detailTextLabel, либо добавить метку secretName при создании ячейки где-то сразу после alloc-and-init новой ячейки. Тогда в configureCell вы устанавливаете только текст метки.

3 голосов
/ 28 июля 2010

Вы добавляете новую метку в представление содержимого ячейки каждый раз, когда ячейка (повторно) используется, так что в итоге вы получаете несколько ярлыков, размещенных друг над другом.Правильный подход - добавить метку только один раз, а затем установить для нее текстовое значение:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.adjustsFontSizeToFitWidth = YES;

        UILabel *secretName = [[UILabel alloc]initWithFrame:(CGRectMake(10, 8, 100, 30))];
        secretName.backgroundColor = [UIColor clearColor];
        secretName.textColor = [UIColor whiteColor];
        secretName.font = [UIFont boldSystemFontOfSize:18];
        secretName.shadowColor = [UIColor colorWithRed:0./255 green:0./255 blue:0./255. alpha:0.7];
        secretName.shadowOffset = CGSizeMake(0, 2.0);
        secretName.tag = 100; // Arbitrary value that you can use later 
        [cell.contentView addSubview:secretName];
        [secretName release]; // Do not forget to release the label!
    }

    // Configure the cell.
    cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UILabel* label = (UILabel*)[cell.contentView viewWithTag:100];
    label.text = [self.secretTitles objectAtIndex:indexPath.row];

    return cell;
}
1 голос
/ 28 июля 2010

Вы должны знать, как UITableView повторно использует ячейки.В вашем коде происходит то, что вы добавляете secretName в ячейки, в которых он уже есть.Вот быстрый переписать ваш код:

//we need a way to find the secretName UILabel in the cell's contentView

enum {
    kSecretNameTag = 255
};

(UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        // we only need to set up the cell when we create it
        cell.textLabel.adjustsFontSizeToFitWidth = YES;
        cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self configureCell:cell];
    }
    // grab the secretName UILabel and set the text
    UILabel* secretName = [cell viewWithTag:kSecretNameTag];
    secretName.text = @"";
    NSLog(@"row = %d", indexPath.row);
    secretName.text = [self.secretTitles objectAtIndex:indexPath.row];
    return cell;
}

(void)configureCell:(UITableViewCell *)cell {
    secretName = [[UILabel alloc]initWithFrame:(CGRectMake(10, 8, 100, 30))];
    secretName.backgroundColor = [UIColor clearColor];
    secretName.textColor = [UIColor whiteColor];
    secretName.font = [UIFont boldSystemFontOfSize:18];
    secretName.shadowColor = [UIColor colorWithRed:0./255 green:0./255 blue:0./255. alpha:0.7];
    secretName.shadowOffset = CGSizeMake(0, 2.0);
    secretName.tag = kSecretNameTag;
    [cell.contentView addSubview:secretName];
}
1 голос
/ 28 июля 2010

Вы добавляете подпредставление для каждой ячейки.Объект ячейки используется повторно.Поскольку API не знает, как вы поиграли с ячейкой, вы отвечаете за все, что вы изменили, помимо стандартов .

Вы должны использовать cell.textLabel или другую существующий член UITableViewCell для отображения ваших данных.

ИЛИ: полностью исключает повторное использование ячейки, но это не очень разумно для повышения производительности.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...