2010-07-28 3 views
0

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

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

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

Жюль

ответ

3

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

-(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; 
} 
+0

Спасибо за помощь ... Решение Vladmir's работает для меня. Наверное, мне нужно прочитать о повторном использовании ячеек !!. большое спасибо Jules – Jules

1

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

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

OR: Откажитесь от повторного использования ячейки все вместе, но это не умная вещь, чтобы сделать производительность.

3

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

1

Вы должны быть осведомлены о пути 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]; 
} 
Смежные вопросы