-->

2014年4月29日火曜日

【UICollectionView】カスタムセルをxibで作成

storyboard上でUICollectionViewを用意して、
xibで作ったUICollectionViewCellのカスタムクラスを配置する

1. file > new > file > UserInterface でviewを選択、ファイル名をmyCell.xib
 ラベルをUICollectionViewCellの上に配置する
2. 同じ名前の.hと.mファイルを作成する
3. myCell.xibのFIle's ownerのCustom ClassをmyCellに

 viewを選択して、identifierをmyCellに
 
  Custom CalssもmyCellに

myCellにプロパティを記述
myCell.h
 
#import 

@interface myCell : UICollectionViewCell

@property (strong, nonatomic) IBOutlet UILabel *cellLabel;


@end
myCell.m
 
#import "myCell.h"

@implementation myCell


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


-(void)awakeFromNib
{
    NSLog(@"bundleLoader waked");
}

@end


4. myCell.xibのFIle's ownerではなく、viewを選択して
 inspectorのoutletから用意したプロパティとxib上のラベルをつなぐ

このやりかたでないと、
 Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x6858780> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key… 

とエラーが...

5. あとはcollectionViewController.mで
 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *identifier = @"myCell";
    static BOOL nibCellLoaded = NO;
    
    if(!nibCellLoaded){
        UINib *nib = [UINib nibWithNibName:@"myCell" bundle:nil];
        [collectionView registerNib:nib forCellWithReuseIdentifier:identifier];
        nibCellLoaded = YES;
    }
    
    
    myCell *cell = (OBWeather*)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];

    return cell;
}
 
 

最後に思ったけど、
クラス名とidentifierって一緒じゃない方がいいのかなあ

0 件のコメント:

コメントを投稿