2013-05-30 2 views
0

После добавления шрифта и тени к некоторым UILabels я заметил, что анимация представления таблиц отстает, когда представление выскользнуто из стека (используется боковое, как FB/Path). Боковой салфетка была гладкой, пока я не добавил тени UILabel.Как оптимизировать cellForRowAtIndexPath: code

Я думаю, что я могу добавить его в неправильное место, так что свойства ярлыков добавляются неправильно. Пожалуйста, обратите внимание на следующий cellForRowAtIndexPath: метод ниже:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString * cellReuseIdentifier = @"cellReuseIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseIdentifier]; 
    } 

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 2, self.view.bounds.size.width, 200)]; 
    imageView.image = [UIImage imageNamed:@"rest.jpg"]; 
    [cell.contentView addSubview:imageView]; 

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 30)]; 

    titleLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"title"]; 
    titleLabel.backgroundColor = [UIColor clearColor]; 

    titleLabel.textColor = [UIColor whiteColor]; 
    [titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:24]]; 
    titleLabel.layer.shadowColor = [[UIColor whiteColor] CGColor]; 
    titleLabel.layer.shadowOpacity = 0.7; 

    [cell.contentView addSubview:titleLabel]; 

    UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 160, cell.bounds.size.width, 30)]; 

    detailLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"description"]; 
    detailLabel.backgroundColor = [UIColor clearColor]; 

    detailLabel.textColor = [UIColor whiteColor]; 
    [detailLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18]]; 
    detailLabel.layer.shadowColor = [[UIColor whiteColor] CGColor]; 
    detailLabel.layer.shadowOpacity = 0.7; 

    [cell.contentView addSubview:detailLabel]; 

    cell.contentView.backgroundColor = [UIColor clearColor]; 


    return cell; 
} 

спасибо за любую помощь.

+2

titleLabel.layer.shouldRasterize = YES; detailLabel.layer.shouldRasterize = ДА; – Amar

+0

@Amar спасибо! что сделал разницу – hanumanDev

+0

Но также проверить ответ от @Wain !! –

ответ

4

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

Создайте все свои подзоны, когда ячейка создана, а затем просто обновите настройки subviews. Что-то вроде:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString * cellReuseIdentifier = @"cellReuseIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseIdentifier]; 

     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 2, self.view.bounds.size.width, 200)]; 
     imageView.tag = 123123; 
     [cell.contentView addSubview:imageView]; 

     UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 30)]; 

     titleLabel.tag = 234234]; 
     titleLabel.backgroundColor = [UIColor clearColor]; 

     titleLabel.textColor = [UIColor whiteColor]; 
     [titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:24]]; 
     titleLabel.layer.shadowColor = [[UIColor whiteColor] CGColor]; 
     titleLabel.layer.shadowOpacity = 0.7; 

     [cell.contentView addSubview:titleLabel]; 

     UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 160, cell.bounds.size.width, 30)]; 

     detailLabel.tag = 345345]; 
     detailLabel.backgroundColor = [UIColor clearColor]; 

     detailLabel.textColor = [UIColor whiteColor]; 
     [detailLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18]]; 
     detailLabel.layer.shadowColor = [[UIColor whiteColor] CGColor]; 
     detailLabel.layer.shadowOpacity = 0.7; 

     [cell.contentView addSubview:detailLabel]; 

     cell.contentView.backgroundColor = [UIColor clearColor]; 
    } 

    UIImageView *imageView = (UIImageView *)[cell viewWithTag:123123]; 
    imageView.image = [UIImage imageNamed:@"rest.jpg"]; 

    UILabel *titleLabel = (UILabel *)[cell viewWithTag:234234]; 
    titleLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"title"]; 

    UILabel *detailLabel = (UILabel *)[cell viewWithTag:345345]; 
    detailLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"description"]; 

    return cell; 
}  
1

Поскольку атрибуты текста никогда не меняются, переместите код, который устанавливает их внутри оператора if. Храните только код, который устанавливает изображение и текст ваших ярлыков вне инструкции if. Ячейки повторно используются, поэтому такие атрибуты, как шрифт и т. Д., Остаются с ячейкой даже после того, как она будет «переработана». В ветке else добавьте код, который находит существующие метки в ячейке. В противном случае вы продолжаете добавлять одну и ту же метку в ячейку несколько раз.

1

Вы добавляете subviews, даже после dequeueing вместо инициализации новой ячейки. Убедитесь, что весь код, который создает и добавляет subviews, выполняется только при инициализации ячейки. Если вам нужно обратиться к представлениям в ячейке для настройки, подкласс UITableViewCell.

Кроме того, тень рендеринга может быть замедляя его тоже добавить shadowpath сделать рендеринг более эффективным:

добавить в свой tableView:cellForRowAtIndexPath: метод:

... 
CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:detailLabel.layer.bounds].CGPath; 
detailLabel.layer.shadowPath = shadowPath; 
... 
0

Заменить код с этим:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString * cellReuseIdentifier = @"cellReuseIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseIdentifier]; 


     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 2, self.view.bounds.size.width, 200)]; 
     imageView.image = [UIImage imageNamed:@"rest.jpg"]; 
     imageView.tag =1; 
     [cell.contentView addSubview:imageView]; 

     UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 30)]; 

     titleLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"title"]; 
     titleLabel.backgroundColor = [UIColor clearColor]; 
     titleLabel.tag = 2; 
     titleLabel.textColor = [UIColor whiteColor]; 
     [titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:24]]; 
     titleLabel.layer.shadowColor = [[UIColor whiteColor] CGColor]; 
     titleLabel.layer.shadowOpacity = 0.7; 

     [cell.contentView addSubview:titleLabel]; 

     UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 160, cell.bounds.size.width, 30)]; 
     detailLabel.tag = 3; 
     detailLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"description"]; 
     detailLabel.backgroundColor = [UIColor clearColor]; 

     detailLabel.textColor = [UIColor whiteColor]; 
     [detailLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18]]; 
     detailLabel.layer.shadowColor = [[UIColor whiteColor] CGColor]; 
     detailLabel.layer.shadowOpacity = 0.7; 


    } 

    UIImageView *tempImgView = (UIImageView *)[cell viewWithTag:1]; 
    tempImgView.image = [UIImage imageNamed:@""];// Here you can set any image by reusing imageview without allocating again and again 

    UILabel *tempLabel; 

    tempLabel = (UILabel *)[cell viewWithTag:2]; 
    tempLabel.text = @"";// Here you can access your title label and can set its properties without allocating again 

    tempLabel = (UILabel *)[cell viewWithTag:3]; 
    tempLabel.text = @"";// Here you can access your detailLabel label and can set its properties without allocating again 


    [cell.contentView addSubview:detailLabel]; 

    cell.contentView.backgroundColor = [UIColor clearColor]; 


    return cell; 
} 
0

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

(UITableViewCell *) Tableview: (UITableView *) Tableview cellForRowAtIndexPath: (NSIndexPath *) indexPath { статическая NSString * cellReuseIdentifier = @ "cellReuseIdentifier"; UITableCustomViewCell * cell = [tableView dequeueReusableCellWithIdentifier: cellReuseIdentifier];

if (cell == nil) 
{ 
    cell = [[UITableCustomViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseIdentifier]; 
} 

cell.imageView.image = [UIImage imageNamed:@"rest.jpg"]; 

cell.titleLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"title"]; 

cell.detailLabel.text = (NSString *)[[publicDataArray objectAtIndex:indexPath.row] objectForKey:@"description"]; 

return cell; 

}

1

Эта статья из Twitter Engineering дает отличный обзор: http://engineering.twitter.com/2012/02/simple-strategies-for-smooth-animation.html

В принципе, вы хотите, чтобы избежать использования подвидов, но вместо того, чтобы обратить ваше содержание непосредственно с кварцем. Это лучшее, что вы можете сделать для повышения производительности. Также: избегайте прозрачности!В инструменты, вы можете также использовать инструмент Core Animation и активировать "Color Blended Layers", чтобы увидеть, где прозрачные мнения быть составлены:

enter image description here

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