1

我有一個UICollectionView,我想用100個UICollectionViewCells填充它,每個UICollectionViewCells都有自己的唯一UILabel和從數組中獲取的文本。我想以編程方式執行此操作(沒有故事板)。UICollectionViewCells與UICollectionView中的數據以編程方式從數組中填充數據

我試過它,因爲下面發佈,但由於某種原因只有第一個單元格正確渲染。

// Setting up the UICollectionView 
- (void)setupCollectionView { 
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 
    CGRect newFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.5); 
    self.collectionView=[[UICollectionView alloc] initWithFrame:newFrame collectionViewLayout:layout]; 
    [self.collectionView setDataSource:self]; 
    [self.collectionView setDelegate:self]; 

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
    [self.collectionView setBackgroundColor:[UIColor clearColor]]; 
    [self.view addSubview:self.collectionView]; 
} 

//Trying to generate the unique cells with data 
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
    cell.backgroundColor = [UIColor yellowColor]; 

    UILabel *label = [[UILabel alloc] initWithFrame: cell.frame]; 
    label.text = [self.array objectAtIndex: indexPath.row]; 
    label.textColor = [UIColor blackColor]; 
    [cell.contentView addSubview:label]; 

    return cell; 
} 

注意:我的數組大小爲100,隨機生成數字。

您的幫助表示讚賞:)

謝謝!

Screenshot

回答

3

陣列的框架應該與它的細胞,而不是它的細胞的框架,誰是作爲indexPath增長起源將增長的邊界。另外,我們不希望無條件地創建標籤,因爲這些單元格會被重用。只有創建一個標籤,如果一個不存在....

UILabel *label = (UILabel *)[cell viewWithTag:99]; 
if (!label) { 
    label = [[UILabel alloc] initWithFrame: cell.bounds]; // note use bounds here - which we want to be zero based since we're in the coordinate system of the cell 
    label.tag = 99; 
    label.text = [self.array objectAtIndex: indexPath.row]; 
    label.textColor = [UIColor blackColor]; 
    [cell.contentView addSubview:label]; 
} 
// unconditionally setup its text 
NSNumber *number = self.myArrayOfRandomNumbers[indexPath.row]; 
label.text = [number description]; 
+0

感謝您的幫助丹。我一直在用這個問題猛撞我的腦袋,直到你出現爲止! 這個問題的確切診斷和解決方案的很好的解釋。 10/10 :) – justinSYDE