繁体   English   中英

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

[英]How to set different different text colour for each cell in UICollectionView?

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

UICollectionView 截图

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

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

- (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; 
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM