我正在尝试创建一个UICollectionViewCell与XIB文件的UICollectionView,我正在创建一个没有XIB文件。
下面是我创建CollectionView的方法:_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:collectionViewFlowLayout];
[_collectionView setDelegate:self];
[_collectionView setDataSource:self];
[_collectionView setBackgroundColor:[UIColor clearColor]];
[_collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:carouselItemReuseIdentifier];
[self.view addSubview:_collectionView];
下面是我如何调用自定义单元格:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:carouselItemReuseIdentifier forIndexPath:indexPath];
[cell refreshWithData];
return cell;
}
在XIB文件中,我将自定义类设置为CustomCell -但是当我加载集合视图时,我只看到矩形-而不是为自定义类创建的XIB。
您需要使用registerNib:forCellWithReuseIdentifier:
注册笔尖,而不是类。注册类只意味着它不知道你在nib中添加了什么。
文档
在viewDidLoad
中注册笔尖:
UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil];
[cv registerNib:nib forCellWithReuseIdentifier:identifier];
和单元格方法:
NSArray *Obj = [[NSBundle mainBundle] loadNibNamed:@"CustomCellXib" owner:self options:nil];
CustomCell *cell = [nibObjects objectAtIndex:0];
Happy Coding:)
尝试像下面这样加载xib单元格
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCellXib" owner:self options:nil];
CustomCell *cell = = [nibObjects objectAtIndex:0];
使用以下语句注册类:
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier: carouselItemReuseIdentifier];