我决定不使用Xib来生成我的自定义UICollectionViewCell
(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);
}
以及:
[self.collectionView registerClass:[StoneCell class] forCellWithReuseIdentifier:@"stoneCell"];
在我的UICollectionView
控制器中。
在我的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 :(得分: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
的无限递归。
答案 1 :(得分: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];