首页 > 解决方案 > UITableViewCell 内的 UICollectionView 的 Obj-C- 数据源?

问题描述

我在 ViewController (DashboardViewController) 中有一个 TableView (self.tableView)。在这个 tableview 内部,我有一个包含 UICollectionView 的自定义单元格。

一切正常,但是为了填充 UICollectionView,我目前正在我的 UITableViewCell 中调用数据,我不想这样做,因为每次向上和向下滚动时,都会调用数据。

是否可以使 UICollectionView 的数据源成为 DashboardViewController 内的 NSMutableArray,而不必在它所在的 UITableViewCell 内填充 NSMutableArray?

我现在的设置:

UITableViewCell.h

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *clientsWeek;

UITableViewCell.m

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
     [self.collectionView registerNib:[UINib nibWithNibName:@"ClientCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ClientCollectionViewCell"];

     [_collectionView setDataSource:self];
     [_collectionView setDelegate:self];

    
    NSMutableDictionary *viewParams1 = [NSMutableDictionary new];
    [viewParams1 setValue:@"cdata" forKey:@"view_name"];
    [DIOSView viewGet:viewParams1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        self.clientsWeek = [responseObject mutableCopy];
        NSLog(@"The people are here %@", self.clientsWeek);
        

        [self.collectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@", [error localizedDescription]);
    }];
    
}

标签: iosobjective-cuitableviewuicollectionview

解决方案


在正确设置CellReuseIdentifier的前提下。

当然,您可以选择获取 中的所有数据DashboardViewController,包括 的数据源UICollectionView。这里需要合并数据。tableview的数据源必须是数组,所以UICollectionView的数据源可以放在数组中。像这样

[
  {
   "UITableViewCellData":{},
   "UICollectionViewData":{}
  },
...
]

当然你也可以使用数据模型对象来替换。

然后你需要向单元格公开一个接收数据源的方法,你可以在其中刷新你的 UICollectionView。

UITableViewCell.h

- (void)cellWithDataSource:(NSDictionary *)dataSource;

UITableViewCell.m

- (void)cellWithDataSource:(NSDictionary *)dataSource{
  NSDictionary *tableViewDataSource = dataSource[@"UITableViewCellData"];
  NSDictionary *collectionViewDataSource = dataSource[@"UICollectionViewData"];
  ...
}

DashboardViewController将数据传递给单元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    // first obtains the datasource of each cell, and passes it to each cell
    [cell cellWithDataSource:datasource];
    return cell;
}

推荐阅读