添加 UICollectionView 作为 UI 的子视图可重用视图重新加载数据不起作用,我错过了什么?



我正在尝试将UICollectionView添加到我的自定义UICollectionReusableView中,在主窗体中我有一个UICollectionView(名为mainView(向用户显示第一级菜单,当用户在mainView中选择单元格时,它将在脚部分展开二级菜单(并调用FolderContentView::loadSubMenus方法(, 以下是我的行不通代码,请帮忙。

.h 文件

@interface FolderContentView : UICollectionReusableView<UICollectionViewDataSource,UICollectionViewDelegate>
-(void) loadSubMenus:(NSArray<EnabledModule*>*) subModules;
@end

.m 文件 #import "FolderContentView.h">

@implementation FolderContentView {
UICollectionView *_collectionView;
NSArray* _subMenus;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = CGSizeMake(100, 100);
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
_collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
_collectionView.delegate = self;
_collectionView.dataSource = self;
}
[_collectionView reloadData];
return self;
}
-(void) loadSubMenus:(NSArray<EnabledModule*>*) subModules {
if(subModules != nil) {
_subMenus = [subModules copy];
} else {
_subMenus = nil;
}
[_collectionView reloadData];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _subMenus!=nil?_subMenus.count:0;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"cell"
forIndexPath:indexPath];
if(!cell){
cell=[[UICollectionViewCell alloc]init];
}
EnabledModule *model = _subMenus[indexPath.row];
cell.hidden = !model.enabled;
UILabel *lblText = [[UILabel alloc] init];
lblText.text = model.moduleName;
[cell.contentView addSubview:lblText];
return cell;
}
@end
  1. 尝试从主线程重新加载数据,这是行不通的。
  2. 将 bp 设置为numberOfItemsInSectionnumberOfItemsInSection,而不是提示。
  3. 尝试将委托和数据源设置为我的主视图的控制器,但也不能工作。

"reloadData not work"到底是什么意思?委托方法是否正常运行或没有任何反应?


1.也许您应该检查代码"将UICollectionView添加到我的自定义UICollectionReusableView在运行时中"。

2.也许你忘了做:

[self addSubview:_collectionView];

3.此代码中的"单元格"不会为零:

UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"cell"
forIndexPath:indexPath];
if(!cell){
cell=[[UICollectionViewCell alloc]init];
}

4.不要这样做:

[cell.contentView addSubview:lblText];

请改用 UICollectionViewCell 的子类。

最新更新