2014-02-19 3 views
2

Я пытаюсь добавить UILabel в мой collectionViewCell. Однако после того, как несколько элементов ячейки начинают перекрываться с данными из ячеек раньше.Текст ячеек сотовой ячейки перекрывается в ячейках

ОБНОВЛЕНИЕ: Это, похоже, происходит на моем телефоне (iphone 5), но не на симуляторе (macbook air) в 2013 году.

Как видно здесь:

enter image description here

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

if(cell == nil) {// do something } 

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

Мой код:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
    TTSong *tempSong = [songArray objectAtIndex:indexPath.row]; 

UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, 150, 40)]; 
    [cellLabel setTextColor:[UIColor whiteColor]]; 
    [cellLabel setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8]]; 
    [cellLabel setFont:[UIFont fontWithName: @"HelveticaNeue-Light" size: 12.0f]]; 
    [cellLabel setNumberOfLines:2]; 
    NSString * labelString = [[tempSong.artist stringByAppendingString:@"\n"] stringByAppendingString:tempSong.title]; 
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:labelString]; 
    NSRange boldedRange = NSMakeRange(0, tempSong.artist.length); 
    [attributedString addAttribute: NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue" size:14.0f] range:boldedRange]; 
    [cellLabel setAttributedText:attributedString]; 
    [cell addSubview:cellLabel]; 

    return cell; 
} 

Вот как я установил размер ячеек:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return CGSizeMake(150, 150); 
} 

Вот как настроить мой collectionView:

- (void)viewDidLoad 
{ 
    songArray = [[NSMutableArray alloc] init]; 

    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 
    _collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout]; 
    [_collectionView setDataSource:self]; 
    [_collectionView setDelegate:self]; 

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
    [_collectionView setBackgroundColor:[UIColor blackColor]]; 

    [self.view addSubview:_collectionView]; 
[super viewDidLoad]; 
} 
+2

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

+0

Спасибо.Итак, если в ячейке уже есть метка, мне нужно сначала ее очистить? Есть ли лучший способ реализовать это? Можете ли вы обнаружить более плохие методы из этого кода? – user1933131

+1

Вы можете очистить его или просто проверить, есть ли он, и не добавлять другого, если есть. Другие способы сделать это - создать ячейку с ее меткой в ​​раскадровке (это самый простой способ imo) или создать собственный класс и добавить метку в свой метод init. – rdelmar

ответ

9

Удалить этикетку и повторно инициализировать ее при отображении ячейки.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
    TTSong *tempSong = [songArray objectAtIndex:indexPath.row]; 

    for (UILabel *lbl in cell.contentView.subviews) 
    { 
     if ([lbl isKindOfClass:[UILabel class]]) 
     { 
      [lbl removeFromSuperview]; 
     } 
    } 

    UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, 150, 40)]; 
    [cellLabel setTextColor:[UIColor whiteColor]]; 
    [cellLabel setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8]]; 
    [cellLabel setFont:[UIFont fontWithName: @"HelveticaNeue-Light" size: 12.0f]]; 
    [cellLabel setNumberOfLines:2]; 
    NSString * labelString = [[tempSong.artist stringByAppendingString:@"\n"] stringByAppendingString:tempSong.title]; 
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:labelString]; 
    NSRange boldedRange = NSMakeRange(0, tempSong.artist.length); 
    [attributedString addAttribute: NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue" size:14.0f] range:boldedRange]; 
    [cellLabel setAttributedText:attributedString]; 
    [cell addSubview:cellLabel]; 

    return cell; 
} 
+0

В результате я использовал теги, чтобы удалить ярлык. – user1933131

+0

отличная идея! спасибо :) –

+1

любой, пожалуйста, помогите с быстрой версией ... –

0

Клетки уже имеет элементы, а также вы создаете (добавление) меток программным путем.

То, что вы должны сделать, это:

1 .Снять UILabels внутри UITableViewCell в UIStoryBoard & & создать Программным.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
    { 
     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
     TTSong *tempSong = [songArray objectAtIndex:indexPath.row]; 

    UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, 150, 40)]; 
     [cellLabel setTextColor:[UIColor whiteColor]]; 
     [cellLabel setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8]]; 
     [cellLabel setFont:[UIFont fontWithName: @"HelveticaNeue-Light" size: 12.0f]]; 
     [cellLabel setNumberOfLines:2]; 
     NSString * labelString = [[tempSong.artist stringByAppendingString:@"\n"] stringByAppendingString:tempSong.title]; 
     NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:labelString]; 
     NSRange boldedRange = NSMakeRange(0, tempSong.artist.length); 
     [attributedString addAttribute: NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue" size:14.0f] range:boldedRange]; 
     [cellLabel setAttributedText:attributedString]; 
     [cell addSubview:cellLabel]; 

     return cell; 
    } 

ИЛИ

2.Add в UILabel годов в раскадровке и использовать ссылку на него & & Не создавать в коде просто см (точка) это.

Используйте Tag Недвижимость, чтобы указать на элементы.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
    { 
     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
     TTSong *tempSong = [songArray objectAtIndex:indexPath.row]; 

    UILabel *cellLabel = (UILabel*)[cell ViewWithTag:25]; 
     [cellLabel setTextColor:[UIColor whiteColor]]; 
     [cellLabel setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8]]; 
     [cellLabel setFont:[UIFont fontWithName: @"HelveticaNeue-Light" size: 12.0f]]; 
     [cellLabel setNumberOfLines:2]; 
     NSString * labelString = [[tempSong.artist stringByAppendingString:@"\n"] stringByAppendingString:tempSong.title]; 
     NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:labelString]; 
     NSRange boldedRange = NSMakeRange(0, tempSong.artist.length); 
     [attributedString addAttribute: NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue" size:14.0f] range:boldedRange]; 
     [cellLabel setAttributedText:attributedString]; 
     // [cell addSubview:cellLabel]; Don't add this again 

     return cell; 
    } 
1

Вам просто нужно отметить свойство «очищает графический контекст» метки в раскадровке.

+0

Это уместно, я задаюсь вопросом, почему downvoted. –

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