如何注册自定义 CollectionViewCell?
How to register custom CollectionViewCell?
到目前为止,我一直在成功使用 UITableViews,但我无法让 UICollectionView 工作。
@interface NewsCollectionViewDataSource : NSObject <UICollectionViewDataSource, UICollectionViewDelegate>
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
TNCollectionViewCell *newscell = nil;
newscell = [collectionView dequeueReusableCellWithReuseIdentifier:newsCellReuseIdentifier forIndexPath:indexPath];
if (!newscell) {
[[NSBundle bundleForClass:[self class]] loadNibNamed:@"TNCollectionViewCell" owner:self options:nil];
}
newscell.newsLabel.text = [[self newsForIndexPath:indexPath] headLine];
return newscell;
}
每次我都会排队:
newscell.newsLabel.text = [[self newsForIndexPath:indexPath] headLine];
newscell 为零。
我是不是注册错了?
在检索 collectionView
的单元格之前的某处(即在 viewDidLoad
中)调用 UICollectionView
的以下方法
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;
在你的情况下会是这样的:
[self.collectionView registerNib:[UINib nibWithNibName:@"TNCollectionViewCell" bundle:nil]
forCellWithReuseIdentifier:newsCellReuseIdentifier];
然后就不需要下面的代码了:
if (!newscell) {
[[NSBundle bundleForClass:[self class]] loadNibNamed:@"TNCollectionViewCell" owner:self options:nil];
}
到目前为止,我一直在成功使用 UITableViews,但我无法让 UICollectionView 工作。
@interface NewsCollectionViewDataSource : NSObject <UICollectionViewDataSource, UICollectionViewDelegate>
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
TNCollectionViewCell *newscell = nil;
newscell = [collectionView dequeueReusableCellWithReuseIdentifier:newsCellReuseIdentifier forIndexPath:indexPath];
if (!newscell) {
[[NSBundle bundleForClass:[self class]] loadNibNamed:@"TNCollectionViewCell" owner:self options:nil];
}
newscell.newsLabel.text = [[self newsForIndexPath:indexPath] headLine];
return newscell;
}
每次我都会排队:
newscell.newsLabel.text = [[self newsForIndexPath:indexPath] headLine];
newscell 为零。
我是不是注册错了?
在检索 collectionView
的单元格之前的某处(即在 viewDidLoad
中)调用 UICollectionView
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;
在你的情况下会是这样的:
[self.collectionView registerNib:[UINib nibWithNibName:@"TNCollectionViewCell" bundle:nil]
forCellWithReuseIdentifier:newsCellReuseIdentifier];
然后就不需要下面的代码了:
if (!newscell) {
[[NSBundle bundleForClass:[self class]] loadNibNamed:@"TNCollectionViewCell" owner:self options:nil];
}