簡體   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