2016-12-07 41 views
0

我决定选择不使用Xib来生成我自定义的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}}这是它应该在6s上。但是,对象stone(以及self)都报告为nil

很显然,这是不正确的,所以我想知道如何正确初始化的单元格。

我也是正常出队的单元格:

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

所以这照顾。

+0

你有没有继承你的UICollectionViewCell StoneCell? – Miknash

+0

是的,肯定是的。 –

+0

愚蠢的问题,你确认你正确地设置你的数据源并正确地委托CollectionView?另外,如果你在故事板上有一个原型单元格,然后告诉该原型单元格它是StoneCell类,那么你可以考虑在你的collectionview中添加一个原型单元格。 – Acludia

回答

0

你的初始化应该是

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

与您最初的实现

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

你有initWithFrame无限递归。

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]; 
相关问题