如何在UICollectionView中为每个单元格设置不同的不同文本颜色?

时间:2017-01-06 09:33:39

标签: ios objective-c

如何为UICollectionViewCell中的每个单元格设置不同的背景颜色。

UICollectionView Screenshot

  1. 文字应该是不同的颜色。(一个=红色,两个=绿色就像 明智的)。
  2. 我希望最后一个单元格“全部选择”我希望这个单元格没有
  3. 任何阴影效果。只有查看全部才能位于中心位置。

2 个答案:

答案 0 :(得分:1)

为了为每个单元格设置随机文本颜色,您可以先创建一个函数来生成这样的随机颜色。

- (UIColor *)getRandomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;
    UIColor *randomColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
    return randomColor;
}

然后在-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath内,您可以将颜色设置为文本标签,如此

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

     // you can do it inside the cell's subclass file also, which might be better
     cell.titleLabel.textColor = [self getRandomColor]; 
     cell.titleLabel.textAlignment = NSTextAlignmentLeft;


    // as for question 3
    // quick way to achieve this would be to check if its the last row 
    // and set the text alignment to center.
    // but calling `count` for every cell has a performance hit
    // so you can save it into a variable outside the delegate

    if (indexPath.row == [dataArray count] - 1]) {
       cell.titleLabel.textAlignment = NSTextAlignmentCenter;
    }

    return cell; 
}

答案 1 :(得分:-1)

如果你想在每个索引单元格上提供特定的颜色,那么你可以提供switch case并将颜色应用于 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath方法否则使用随机通过调用某个函数来获取随机颜色。