如何为UICollectionViewCell
中的每个单元格设置不同的背景颜色。
答案 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方法否则使用随机通过调用某个函数来获取随机颜色。