Как установить UILabel на UICollectionViewCell?

Я делал это несколько десятков раз с пользовательскими и стандартными ячейками UITableView. Все мои розетки подключены. UILabel — это подвид моего UICollectionViewCell в IB. Мой объект UICollectionViewCell наследует правильный класс в инспекторе идентификации.

Как установить UILabel на UICollectionViewCell?

MyCell.m

-(void)setCellName:(NSString *)cellName {
    self.cellLabel.text = cellName;
}

ViewController.m

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ADMCell *cell = 
     (ADMCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"ADMCell" 
                                                          forIndexPath:indexPath];
    [cell setCellName:[NSString stringWithFormat:@"%d",[indexPath row]]];

    return cell;
}

Вывод cell.debugDescription:

2013-05-15 22:05:40.191 ProductName[857:c07] cell.debugDescription: 
   <ADMCell: 0xb35c890; baseClass = UICollectionViewCell; 
   frame = (245 266; 70 80); layer = <CALayer: 0xb35c780>>`

person palmi    schedule 15.05.2013    source источник
comment
Установили ли вы ячейку в IB правильный идентификатор ADMCell, чтобы она правильно удалялась из очереди?   -  person Dan Fairaizl    schedule 16.05.2013
comment
можете ли вы NSLog(%@,cell.debugDescription) после того, как вы присвоили заголовок? На всякий случай, если ячейка равна нулю... И подтвердите, что зарегистрирована только @AMDCell.   -  person Alex    schedule 16.05.2013
comment
Так какая у тебя проблема? self.cellLabel равен нулю? Является ли ячейка неправильным типом ячейки? Мы не знаем, что случилось, если ты нам не скажешь.   -  person Caleb    schedule 16.05.2013
comment
Дэн Файрайзл, идентификатор установлен как ADMCell. Алекс, я включил вывод выше. Извините за отсутствие подробностей. @Caleb setCellName: никогда не устанавливает метку для ячейки. Посмотрите на этот снимок экрана.   -  person palmi    schedule 16.05.2013
comment
мммм... хорошо.. если вы установите точку останова в -cellForItemAtIndexPath:(NSIndexPath *)indexPath и проверите cell.cellLabel, содержит ли он ожидаемый текст? А текстовая метка, на всякий случай, на переднем плане нет ничего, что затуманивает вид?   -  person Alex    schedule 16.05.2013


Ответы (1)


попробуйте это, это работает для меня.

файл cell.h

     #import <UIKit/UIKit.h>

     @interface CelebretiesCollectionViewCell : UICollectionViewCell
     {
         UIImageView *imgHairPhoto;
     }
     @property (nonatomic, retain) IBOutlet UILabel *titleLabel;
     @property (nonatomic, retain) IBOutlet UIImageView *imgHairPhoto;

файл cell.m

     @synthesize titleLabel,imgHairPhoto;

     - (id)initWithFrame:(CGRect)frame
     {
         self = [super initWithFrame:frame];
         if (self) {

             // Initialization code
             NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"CelebretiesCollectionViewCell" owner:self options:nil];

             if ([arrayOfViews count] < 1) {
                 return nil;
             }

             if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
                 return nil;
             }

             self = [arrayOfViews objectAtIndex:0];

         }
         return self;
     }
     @end

// Берем collectionviewCell в xib и делаем выход на CollectionViewXib.

введите здесь описание изображения

/////////////////////////////////////

теперь использование представления коллекции

        viewdidload method

          [self.YourCollectionViewObj registerClass:[CelebretiesCollectionViewCell class] forCellWithReuseIdentifier:@"celebretiesCollectionViewCell"];


       //Datasource and delegate method
       - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
                   return [arrFavorites count];///Your array count
       }
       - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
           return 1;
       }
       - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

           static NSString *CellIdentifier = @"celebretiesCollectionViewCell";
           CelebretiesCollectionViewCell *cell;
           cell = (CelebretiesCollectionViewCell *)[YourCollectionViewObj dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
             cell.frame=CGRectMake(0, 0, 150, 120);// set frame as per xib

             cell.imgHairPhoto.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:strPath]];
               cell.titleLabel.text = shrObj.strCelebrityName;
               return cell;
       }

       - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:        (UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
           return UIEdgeInsetsMake(-10, 0, 0, 0); //set as per your requirements.
       }
person SAMIR RATHOD    schedule 16.05.2013
comment
Путешествие. Я попробую это, когда у меня будет немного времени. Я полагаю, что этот метод все еще должен работать, поскольку я использую раскадровки. Моя ячейка на раскадровке должна просто наследоваться от класса, например, CelebretiesCollectionViewCell или ADMCell. Правильный? - person palmi; 16.05.2013
comment
да, используйте имя своей ячейки вместо CelebretiesCollectionViewCell - person SAMIR RATHOD; 16.05.2013
comment
Это помогло. Забавно, насколько это похоже на пользовательский UITableViewCell. Я должен был сначала попробовать это. Спасибо, сэр! - person palmi; 20.05.2013