2011-12-28 3 views
0

У меня есть TableView, количество строк которого зависит от количества NSStrings в именах NSMutableArray.Неправильное обновление содержимого UITableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return friendsNames.count + 1; 
} 

Также каждая строка отображает NSString в соответствующем индексе имен друзей. Все кажется очень простым. Но когда я удаляю строку из имен друзей и использую метод reloadData, возникает странная вещь: UITableView удаляет LAST строку, а не строку со строкой, которая была просто удалена из имен друзей. Не могли бы вы объяснить мне, что происходит, и что я должен сделать, чтобы исправить это?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *MyIdentifier = [NSString stringWithFormat:@"MyIdentifier %i", indexPath.row]; 

MyTableCell *cell = (MyTableCell *)[friendsList dequeueReusableCellWithIdentifier:MyIdentifier]; 

if (cell == nil) { 
    cell = [[[MyTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; 

    //create columns 
    for (int i = 0;i < 6;i++) 
     [cell.contentView addSubview:[self createGrid:i :indexPath]]; 
} 
return cell; 
} 

и вот метод, который создает columns.it это вызывается из cellForRowAtIndexPath, и это довольно некрасиво

- (UILabel *)createGrid:(int)columnIndex :(NSIndexPath *)indexPath 
    { 
CGFloat widths [6] = {35.0,62.0,35.0,35.0,35.0,35.0};//two arrays holding widths of the columns and points where left sides begin 
CGFloat leftSides [6] = {0.0,35.0,97.0,132.0,167.0,202.0}; 

NSArray *titles = [[[NSArray alloc] initWithObjects:@"Status",@"ID",@"Wins",@"Losses",@"Withdrawls",@"Win %", nil] autorelease]; 

UILabel *columnLabel = [[[UILabel alloc] initWithFrame:CGRectMake(leftSides[columnIndex],0.0,widths[columnIndex], friendsList.rowHeight)] autorelease]; 

if (indexPath.row == 0) 
    columnLabel.text = [titles objectAtIndex:columnIndex]; 

else 
{ 
    switch (columnIndex) 
    { 
     case 0: 
     { 
      BOOL isOnline = [[[receivedUsers objectForKey:[friendsNames objectAtIndex:indexPath.row - 1]] objectAtIndex:0] boolValue]; 
      columnLabel.text = isOnline [email protected]"On" :@"Off"; 
     } 
      break; 
     case 1: 
      columnLabel.text = [friendsNames objectAtIndex:indexPath.row - 1]; 
      break; 
     case 2: 
      columnLabel.text = [NSString stringWithFormat:@"%i",[[[receivedUsers objectForKey:[friendsNames objectAtIndex:indexPath.row - 1]] objectAtIndex:1] intValue] ]; 
      break; 
     case 3: 
      columnLabel.text = [NSString stringWithFormat:@"%i",[[[receivedUsers objectForKey:[friendsNames objectAtIndex:indexPath.row - 1]] objectAtIndex:2] intValue] ]; 
      break; 
     case 4: 
      columnLabel.text = [NSString stringWithFormat:@"%i",[[[receivedUsers objectForKey:[friendsNames objectAtIndex:indexPath.row - 1]] objectAtIndex:3] intValue] ]; 
      break; 
     case 5: 
      columnLabel.text = [NSString stringWithFormat:@"%f",[[[receivedUsers objectForKey:[friendsNames objectAtIndex:indexPath.row - 1]] objectAtIndex:4] floatValue] ]; 
      break; 
    } 
} 

columnLabel.layer.borderColor = [[UIColor blackColor] CGColor]; 
columnLabel.layer.borderWidth = 1.0; 
columnLabel.font    = [UIFont systemFontOfSize:8.0]; 
columnLabel.textAlignment  = UITextAlignmentCenter; 
columnLabel.textColor   = [UIColor blackColor]; 
columnLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight; 

return columnLabel; 
} 
+0

Как удалить строки из подлинных имен? Если у вас NSLog friendsName есть правильные данные? –

+1

Можете ли вы показать код, в котором вы удаляете объект? Я думаю, проблема может быть там. – MadhavanRP

+0

У вас 'NSLog' ваш массив, чтобы убедиться, что вы удаляете то, что считаете себя? –

ответ

2

Это многоразовая проблема клетки. Просто измените свой код:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *myIdentifier = [NSString stringWithFormat:@"MyIdentifier %i", indexPath.row]; 

    MyTableCell *cell = (MyTableCell *)[friendsList dequeueReusableCellWithIdentifier:myIdentifier]; 

    if (cell == nil) { 
     //Create a new cell 
     cell = [[[MyTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:myIdentifier] autorelease]; 
    } 

    //Configure the cell 
    //Remove all columns 
    for(UIVIew *subview in cell.contentView.subviews) { 
     [subview removeFromSuperview]; 
    } 
    //Create columns 
    for (int i = 0;i < 6;i++) { 
     [cell.contentView addSubview:[self createGrid:i :indexPath]]; 
    } 
    return cell; 
} 
+0

Подумайте также, чтобы использовать IB для создания ячейки с 6 IBOutlets с вашими столбцами. Используйте этот вид кода http://stackoverflow.com/questions/540345/how-do-you-load-custom-uitableviewcells-from-xib-files и измените метод createGrid в методе configureCell: cell с кодом, подобным ячейке. label1.text = [friendsNames objectAtIndex: indexPath.row - 1]; –

Смежные вопросы