[英]How to set different different text colour for each cell in UICollectionView?
为了为每个单元格设置随机文本颜色,您可以首先创建一个函数来生成这样的随机颜色。
- (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.