2016-12-07 8 views
0

XYを使用してカスタムを生成することにしました。UICollectionViewCellStoneCell)を適切に初期化する方法に苦労しました。 Nibを使用せずにプログラムでUICollectionViewCellを初期化する方法

は私が実装さ:私の UICollectionViewコントローラに

[self.collectionView registerClass:[StoneCell class] forCellWithReuseIdentifier:@"stoneCell"]; 

- (CGSize)collectionView:(UICollectionView *)collectionView 
        layout:(UICollectionViewLayout *)collectionViewLayout 
    sizeForItemAtIndexPath:(NSIndexPath *)indexPath { 
    CGSize size = [MainScreen screen]; 
    CGFloat width = size.width; 
    CGFloat item = (width*60)/320; 
    return CGSizeMake(item, item); 
} 

など。私StoneCell.m

、私は次のことを試してみました:

-(id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     StoneCell* stone = [[StoneCell alloc] initWithFrame:frame]; 
     self = stone; 
    } 
    return self; 
} 

が、無駄に。私がビルドして実行すると、私は墜ちますself = [super initWithFrame:frame];フレームの値をチェックすると、正しく設定されているのは{{0,0},{70,70}}で、これは6秒でなければなりません。しかしながら、オブジェクトstone(ならびにselfと同様)は、ともにと報告されている。

明らかにこれは正しくないので、セルを適切に初期化する方法を知りたいと思っていました。

私はまた、適切にセルをデキューしています。そのために世話をしています

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
       cellForItemAtIndexPath:(NSIndexPath *)indexPath 

+0

UICollectionViewCellからStoneCellを継承しましたか? – Miknash

+0

はい、間違いはありません。 –

+0

愚かな質問、あなたは正しくあなたのデータソースを設定し、CollectionViewのために適切に委任したことを確認しましたか?また、ストーリーボード上にプロトタイプセルを追加して、そのプロトタイプセルにStoneCellクラスであることを伝えれば、コレクションビューにプロトタイプセルを追加することもできます。 – Acludia

答えて

0

あなたの初期化子は、あなたがinitWithFrameの無限再帰を持って、あなたのオリジナルの実装

-(id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     StoneCell* stone = [[StoneCell alloc] initWithFrame:frame]; 
     self = stone; 
    } 
    return self; 
} 

- (instancetype)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    return self; 
} 

でなければなりません。

0

// AMAImageViewCell.h

#import <UIKit/UIKit.h> 

@interface AMAImageViewCell : UICollectionViewCell 

@property (strong, readonly, nonatomic) UIImageView *imageView; 

@end 

// AMAImageViewCell.mでは

@implementation AMAImageViewCell 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     _imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds]; 

     _imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 
     _imageView.clipsToBounds = YES; 
     _imageView.contentMode = UIViewContentModeScaleAspectFill; 

     _imageView.layer.cornerRadius = 0.0; 

     [self.contentView addSubview:_imageView]; 
    } 
    return self; 
} 


@end 

/******あなたは*******を使用する必要がクラスで***/

[self.collectionView registerClass:[AMAImageViewCell class] forCellWithReuseIdentifier:ImageCellIdentifier]; 

// cellForItemAtIndexPathで

AMAImageViewCell *cell = [collectionViewLocal dequeueReusableCellWithReuseIdentifier:ImageCellIdentifier 
                    forIndexPath:indexPath]; 
関連する問題