我尝试在运行时将 UICollectionView 添加到我的自定义 UICollectionReusableView 中,在主窗体中,我有一个 UICollectionView(名为 mainView)来向用户显示第一级菜单,当用户在 mainView 中选择单元格时,它将展开第二级 footer 菜单(并调用FolderContentView::loadSubMenus方法), 以下是我无法工作的代码,请帮忙。
.h 文件
@interface FolderContentView : UICollectionReusableView<UICollectionViewDataSource,UICollectionViewDelegate>
-(void) loadSubMenus:(NSArray<EnabledModule*>*) subModules;
@end
.m 文件 #导入“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
- 尝试从主线程重新加载数据,它不会工作。
- 将 bp 设置为 numberOfItemsInSection numberOfItemsInSection,而不是提示。
- 尝试将 delegate 和 dataSource 设置为我的 mainView 的 Controller ,但也不起作用。
最佳答案
“reloadData 不工作”到底是什么意思?委托(delegate)方法是否正确运行或什么都没发生?
1.也许你应该检查代码'add UICollectionView to my custom UICollectionReusableView in runtime'。
2.也许你忘了做:
[self addSubview:_collectionView];
3.这段代码中的'cell'不会为nil:
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"cell"
forIndexPath:indexPath];
if(!cell){
cell=[[UICollectionViewCell alloc]init];
}
4.不要这样做:
[cell.contentView addSubview:lblText];
改用 UICollectionViewCell 的子类。
关于ios - 添加 UICollectionView 作为 UICollectionReusableView reloadData 的 subview 不起作用,我想念什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823069/