2017-06-15 100 views
1

按照此answer所以我能夠以編程方式創建UICollectionView。但是當我嘗試將子視圖添加到UICollectionViewCell時,我找不到更好的解決方案。這是一些最上回答如何等都實現以編程方式將子視圖添加到UICollectionView中

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
    cell.backgroundColor = [UIColor redColor]; 
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)]; 
    image.image = /*some image*/ 
    [cell addSubview:image]; 
    return cell; 
} 

也許我錯了,但使用UICollectionView的目的是不回收的,因爲和重用優化服務表現?如果使用上面的代碼時,用戶滾動不是它會增加UIImageViewUICollectionViewCell子視圖當dequeueReusableCellWithReuseIdentifier得到觸發器?

那麼有什麼更好的方法來做到這一點?我無法使用UITableView,因爲我需要水平滾動技術。

注意:我需要以編程方式創建它,而不使用xib。

回答

1

是的,它會每次添加imageView當您的收藏視圖將滾動!這不是一個好方法。現在,你可以做的是,在你的collectionview cell中取一個圖像視圖,我的意思是在界面構建器(xib或任何你使用的故事板)和cellForItemAtIndexPath只需show or hide圖像視圖根據需要或根據需要改變圖像!

更新:

如果您有創建集合視圖編程,那麼你可以在你的cellForItemAtIndexPath設置一些標誌!拿一個標誌並在添加imageview後設置它。你可以聲明imageviewflag爲全局變量。類似的,

if (!isImageAdded) { 

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
    cell.backgroundColor = [UIColor redColor]; 
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)]; 
    imageView.image = /*some image*/ 
    [cell addSubview:image]; 
    isImageAdded = YES; 
} 
else{ 

    imageView.image = /*some image*/ 
} 
+0

Thx for reply。我知道如何使用XIB創建它,但我需要的是在不使用XIB或故事板的情況下以編程方式創建它。可能嗎? –

+0

檢查我的更新回答! – Lion

+0

Thx,我需要 –

相關問題