У меня странная проблема с использованием метода 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
для фона и цвет текста, позвольте мне напомнить вам, что это все еще находится в стадии тестирования , о нем позаботятся позже.
вы можете сделать подкласс uitableViewCell и переопределить метод prepareForReuse для управления повторным использованием. Кроме того, вы могли бы показать еще один код в - (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) метод indexPath? – BergP
Кажется, что вы устанавливаете (настраиваете) свои подпрограммы внутри блока if() {} – BergP
. Отправьте полный код того, как вы добавляете эти подпункты и заполняете их данными. – Eugene