2

Я создаю NSMutableAttributedString в cellForItemAtIndexPath метод моего представления коллекции. Я использую NSTextAttachment для вставки изображений в текст.Является ли NSMutableAttributedString с созданием NSTextAttachment в cellForItemAtIndexPath плохой идеей (производительность или дизайн мудрым)?

Это плохая идея? В настоящее время производительность прокрутки кажется хорошей, но я не уверен, есть ли лучший способ? Будет ли кэширование всего NSMutableAttributedString в NSMutableDictionary лучше для второго прокрутки?

Этот вопрос может быть применен и к UITableview, используя cellForRowAtIndexPath.

Код:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    CellView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[CellView reuseIdentifier] forIndexPath:indexPath]; 

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; 
    attachment.image = [UIImage imageNamed:@"eye"]; 
    attachment.bounds = CGRectMake(0, -2.5, 14,14); 
    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; 

    NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@""]; 
    [myString appendAttributedString:attachmentString]; 

    [myString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" 19K "]]; 

    NSTextAttachment *attachment2 = [[NSTextAttachment alloc] init]; 
    attachment2.image = [UIImage imageNamed:@"heart"]; 
    attachment2.bounds = CGRectMake(0, -2.5, 14,14); 
    NSAttributedString *attachmentString2 = [NSAttributedString attributedStringWithAttachment:attachment2]; 

    [myString appendAttributedString:attachmentString2]; 

    [myString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" 13K "]]; 

    [myString enumerateAttribute:NSFontAttributeName inRange:(NSRange){0,[myString length]} options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) { 
     [myString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"AvenirNext-Medium" size:12] range:range]; 
     [myString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithWhite:1 alpha:1] range:range]; 
    }]; 



    NSMutableAttributedString *titletext= [[NSMutableAttributedString alloc] initWithString:[self checkIfBig:indexPath]?[NSString stringWithFormat:@"\nThe Underground Railway"]:[NSString stringWithFormat:@"\nPink Oasis"]]; 

    [titletext enumerateAttribute:NSFontAttributeName inRange:(NSRange){0,[titletext length]} options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) { 
     [titletext addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"AvenirNext-Medium" size:24] range:range]; 
     [titletext addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range]; 
    }]; 

    [myString appendAttributedString:titletext]; 

    if ([self checkIfBig:indexPath]){ 
     NSMutableAttributedString *subtitletext= [[NSMutableAttributedString alloc] initWithString:@"\nLorem Ipsum is simply dummy text of the printing and typesetting industry."]; 

     [subtitletext enumerateAttribute:NSFontAttributeName inRange:(NSRange){0,[subtitletext length]} options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) { 
      [subtitletext addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"AvenirNext-Medium" size:14] range:range]; 
      [subtitletext addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range]; 
     }]; 
     [myString appendAttributedString:subtitletext]; 
    }; 

    if ([self checkIfBig:indexPath]){ 
     NSMutableAttributedString *subtitletext= [[NSMutableAttributedString alloc] initWithString:@"\n\n#HORROR #BLOOD"]; 

     [subtitletext enumerateAttribute:NSFontAttributeName inRange:(NSRange){0,[subtitletext length]} options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) { 
      [subtitletext addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"AvenirNext-MediumItalic" size:14] range:range]; 
      [subtitletext addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range]; 
     }]; 
     [myString appendAttributedString:subtitletext]; 
    }; 

    cell.titleLabel.attributedText=myString; 


    return cell; 
} 
+0

создать одну функцию в файле класса и просто просто вызвать ее и передать данные, поэтому ее очень просто использовать, почему вы пишете весь этот код в методе tableviewcellrowatindex –

ответ

2

Как правило, данные должны быть собраны один раз перед табличном или просмотр коллекции будет загружен. В вашем текущем коде, когда пользователь прокручивает назад и вперед, вы снова и снова воссоздаете одни и те же данные. Это довольно неэффективно.

Все ваши данные должны быть в одном массиве (или массиве массивов, если у вас несколько разделов). Ваш cellForRow|ItemAtIndexPath должен просто получить объект из массива, и его свойства должны быть использованы для заполнения ячейки.

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

Когда все сделано правильно, cellForItemAtIndexPath в вашем вопросе должен быть менее 5 строк кода.

+0

потрясающе, спасибо! Поэтому перед созданием «cellForRowItemAtIndexPath» я должен создать все «NSMutableAttributedString» заранее? –

+0

Начните с этого и посмотрите, как ваша производительность. Если все это первоначальное создание занимает слишком много времени, есть способы улучшить этот подход. – rmaddy

+0

удивительный, спасибо! –

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