如何从UICollectionView单元格设置UIImageView的背景颜色

时间:2013-06-05 04:40:33

标签: objective-c uiimageview uicollectionview uicolor uicollectionviewcell

我没有使用过很多UICollectionView所以这可能是不可能的,但从来没有伤害过要求:)

每个单元格设置为不同的颜色。

我想要做的是点击一个单元格并推送到另一个UIViewController,它将包含与所选颜色相同的UIImageView。

现在我可以更改第二个UIViewController视图的颜色,但不能更改其中的UIImageView的颜色。

以下是我的一些代码:

 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
 {
     [collectionView deselectItemAtIndexPath:indexPath animated:YES];

     ImageViewController * imageVC = [[ImageViewController alloc] initWithNibName:@"ImageViewController" bundle:nil];

     self.flatColor = [self colorForRow:indexPath.row];

     [self.navigationController pushViewController:imageVC animated:YES];

     imageVC.colorImageView.backgroundColor = _flatColor;
 }

 - (UIColor *)colorForRow:(NSInteger)row
 {
     UIColor *color;

     switch (row)
     {
         case 0:
             color = [UIColor redColor];
             break;
         case 2:
             color = [UIColor greenColor];
             break;
         case 4:
             color = [UIColor blueColor];
             break;
         default:
             color = [UIColor yellowColor];
             break;
     }

     return color;
 }

编辑:

修正了问题。

我不得不重新安排一些代码。需要首先完全加载新的viewController,然后更改UIImageView的backgroundColor

1 个答案:

答案 0 :(得分:0)

请尝试以下代码。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
 {
     [collectionView deselectItemAtIndexPath:indexPath animated:YES];

     ImageViewController * imageVC = [[ImageViewController alloc]    initWithNibName:@"ImageViewController" bundle:nil];

     self.flatColor = [self colorForRow:indexPath.row];

     // This does not work

    [imageVC.colorImageView setBackgroundColor:_flatColor];

    //imageVC.colorImageView.backgroundColor = _flatColor;

     // This works
     //imageVC.view.backgroundColor = _flatColor;

     [self.navigationController pushViewController:imageVC animated:YES];
 }