2013-08-24 2 views
0

У меня странная проблема с использованием метода dequeueReusableCellWithIdentifier:UITableView. Не уверен, что я недостаточно разбираюсь в этом методе или это просто странно. Здесь идет:UITableViewCell вид после удаления из UITableView не пуст

Im используя UITableView который представляет некоторые данные для пользователей, так и внутри моего
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath Я использую метод Dequeue так:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; 
    if (!cell) 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; 

Затем добавить несколько подвидов в contentView собственность клетка. Когда вы немного прокручиваете мою таблицу, я вижу те ранее добавленные subview, т. Е. Ячейка не пуста, но заполнена «старыми» данными. Если я не удаляю, и только alloc-init каждый раз новый, ячейки пустые, но я вижу немного больше потребления памяти, и именно это я пытаюсь немного сбить. Я использую ARC, если что-то здесь.

Что и как мне решить проблему? Я попытался запустить цикл for через подпункты представления содержимого и [view removeFromSuperview], который удаляет предыдущие представления и немного снижает потребление памяти. Но действительно ли это необходимо? Или есть лучший способ?

EDIT здесь некоторый код, как я добавить подвидов

cell.backgroundView = [[UIView alloc] initWithFrame:cell.frame]; 
cell.backgroundColor = kClearColor; //defined to [UIColor clearColor] 
cell.selectionStyle = UITableViewCellSelectionStyleNone; 

if (indexPath.row == 0) 
{ 
    UIImageView *shine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)]; 
    shine.image = [UIImage imageNamed:@"top_shine_1"]; 
    [cell.backgroundView addSubview:shine]; //its a gradient thats why its added to background 

    UILabel *appLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, winSize.height * 0.027, 250, 33)]; 
    appLabel.backgroundColor = kClearColor; //defined to clear color 
    appLabel.textColor = kWhiteColor; //defined to white color 
    appLabel.text = [viewOrder objectAtIndex:tableView.tag]; //just an array from where I get the required text 
    appLabel.font = kStandardFontOfSize(30); //defined to a specific font 

    [cell.contentView addSubview:appLabel]; 

    UIButton *settingsButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    settingsButton.frame = CGRectMake(10, winSize.height * 0.0377, 31, 21); 
    [settingsButton setImage:[UIImage imageNamed:@"settings_button"] forState:UIControlStateNormal]; 
    [settingsButton addTarget:self action:@selector(settings:) forControlEvents:UIControlEventTouchUpInside]; 

    [cell.contentView addSubview:settingsButton]; 

    return cell; //here I just return it since this is all the config the first cell needs 
} 

NSString *app = [viewOrder objectAtIndex:tableView.tag]; 
NSArray *boxes = [[plist secondObjectForKey:@"order" parent:app] componentsSeparatedByString:@";"]; 

//Add necessary shines or create the last logotype cell - just some details and stuff, all are just images 
if (indexPath.row == 1) 
{ 
    UIImageView *shine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 282.5)]; 
    shine.image = [UIImage imageNamed:@"top_shine_2"]; 

    [cell.backgroundView addSubview:shine]; 
} 
else if (indexPath.row == 2) 
{ 
    UIImageView *shine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, winSize.width, 150)]; 
    shine.image = [UIImage imageNamed:@"main_shine"]; 

    [cell.backgroundView addSubview:shine]; 
} 
else if (indexPath.row == boxes.count + 1) 
{ 
    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(111.5, 25, 97, 20)]; 
    logo.image = [UIImage imageNamed:@"cell_logo"]; 

    [cell.backgroundView addSubview:logo]; 
    return cell; 
} 

NSString *databox = [boxes objectAtIndex:indexPath.row - 1]; 
UIView *view; //Main subview to be added to the cell 

/* 
    here I have a class that creates a view with a bunch of subviews added to that view, the view is then assigned to 'view'; kinda like 
view = [someAssembler assembleViewWith:options.....]. all are basically UILabels or ImageViews added to the main view 
*/ 

[cell.contentView addSubview:view]; //and here this 'main view' is added as a subview, this view is still visible after the cell has been dequeued and the shines are as well 

return cell; 

Перед тем, как начать критиковать, почему им не с помощью одного UIColor для фона и цвет текста, позвольте мне напомнить вам, что это все еще находится в стадии тестирования , о нем позаботятся позже.

+0

вы можете сделать подкласс uitableViewCell и переопределить метод prepareForReuse для управления повторным использованием. Кроме того, вы могли бы показать еще один код в - (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) метод indexPath? – BergP

+0

Кажется, что вы устанавливаете (настраиваете) свои подпрограммы внутри блока if() {} – BergP

+0

. Отправьте полный код того, как вы добавляете эти подпункты и заполняете их данными. – Eugene

ответ

2

[cell.backgroundView addSubview:shine]; эти строки кода являются проблемой в вашем случае.

Вы должны создать полную многоразовую ячейку в блоке if (! Cell) и повторно перенастроить их каждый раз, когда вызывается cellForRow. Для каждой уникальной ячейки следует использовать уникальный идентификатор повторного использования. Например, если у вас несколько ячеек с разложенными подзонами, вы должны использовать для них разные идентификаторы.

В вашем конкретном примере ячейки должны быть созданы в блоках if (indexPath.row == 1).

static NSString *cellIdentifier = @"cell"; 
UITableViewCell *cell = nil; 

if (indexPath.row == 0) { 
    cellIdentifier = @"topCell"; 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    if (!cell) { 
    // create the cell and add the necessary subviews for indexPath row 0 
    } 
    return cell; 
} 
else if (indexPath.row == 1) { 

} 

//etc. 

}

Вы должны создать «основной подвид» для каждой ячейки в камерном блоке! С этим подходом, хотя, так что вы, вероятно, следует искать в подклассов клетку.

+0

О, я вижу. Я не понял, как работает dequeuereusablecellwithidentifier. До сих пор у меня всегда был простой «UITableView», в котором все ячейки были одинаковыми и только разными текстами, поэтому этот метод работал. Спасибо. – Majster