2015-12-03 52 views
0

我正試圖讓集合視圖單元格上的背景圖像和文本。當我構建並運行它時,它們有時會顯示在模擬器中,有時它們甚至不會在我不更改代碼時出現。UICollectionViewCell有時不會顯示

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 

    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat frameWidth = screenRect.size.width - 40; 
    CGFloat frameHeight = screenRect.size.height - 20; 

    _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(20, 20, frameWidth, frameHeight) collectionViewLayout:layout]; 
    [_collectionView setDataSource: self]; 
    [_collectionView setDelegate: self]; 

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
    [_collectionView setBackgroundColor:[UIColor clearColor]]; 

    [self.view addSubview:_collectionView]; 
} 


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return [self.articles count]; 
} 


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 

    UILabel *articleTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, 40)]; 
    NSDictionary *article = self.articles[indexPath.row]; 


    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: article[@"image"]]]; 

    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]]; 

    articleTitle.text = article[@"title"]; 
    articleTitle.textColor = [UIColor whiteColor]; 
    [cell.contentView addSubview:articleTitle]; 


    return cell; 
} 

「物品」是標題,圖片和網址鍵JSON對象。他們似乎在細胞出現時工作,但正如我所說的,他們並不總是表現出來。

這是我的第一個應用程序,所以任何幫助將非常感激。

+0

這可能與您如何加載數據有關。你可以發佈調用reloadData的代碼嗎? – Champoul

回答

0

部分的數量將取決於文章數量。 嘗試在其中放置斷點,如果收集視圖數據源不會獲取任何要顯示的數據,則您的文章數組可能爲空。 或者,如果self.articel引用數組,然後嘗試替換行 NSDictionary * article = self.articles [indexPath.row]; With NSDictionary * article = [self.articles objectatIndexPath:indexPath.row];

或發佈您的完整代碼,以便我們可以看到其他可能的錯誤。

相關問題