繁体   English   中英

如何将ViewController内部的数组数据传递给UICollectionView自定义单元格?

[英]How to pass array data inside ViewController to UICollectionView Custom Cell?

我在自定义'UICollectionViewCell'中创建一个tableView,在ViewController中,我有一个数组,其中包含要在TableView中每行显示的数据。 因此,我想将此数组的数据传递到自定义单元格(包含tableview委托方法)。

我这样做,但没有帮助。

在“ GroupCollectionViewCell.m”内部

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *groupTableIdentifier = @"DeptGroupTable";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:groupTableIdentifier];

    if (cell == nil) {

    }
    RoadmapViewController *vc = [[RoadmapViewController alloc] init];
    cell.textLabel.text =[vc.grouplist objectAtIndex:indexPath.row];
    return cell;
}

在“ RoadViewController.m”中

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{
    GroupCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[GroupCollectionViewCell alloc] init];
        // [cell.groupData addObjectsFromArray:_grouplist];
        //:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    return cell;
}

注意 -如果要传递的数组和groupData是自定义单元格内的空白数组,则为groupList。

CollectionViewCell内创建一个MutableArray对象,并像这样创建一个方法

@property (strong, nonatomic) NSMutableArray *arrObj;

-(void)loadTableData(NSMutableArray*)arr {
     self.arrObj = arr;
     [self.tableView reloadData];
     //Now used this arrObj in your delegate and datasource method
}

之后,以这种方式从cellForItemAtIndexPath调用此函数

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 

{
    GroupCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[GroupCollectionViewCell alloc] init];
        // [cell.groupData addObjectsFromArray:_grouplist];
        //:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    [cell loadTableData:arr];
    return cell;
}

希望这会帮助你。

如果使用alloc init来创建RoadmapViewController并从中获取grouplist ,显然vc.grouplist将返回nil

删除以下两行:

RoadmapViewController *vc = [[RoadmapViewController alloc] init];
cell.textLabel.text =[vc.grouplist objectAtIndex:indexPath.row];

并执行以下操作:

cell.textLabel.text =[_groupData objectAtIndex:indexPath.row];

然后在“ RoadViewController.m ”中添加以下方法:

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(GroupCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{        
    cell.groupData = _groupList;
    [collectionView reloadData];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM