简体   繁体   English

如何更改特定UIViewCollectionCell的背景颜色?

[英]How can I change the background color of an specific UIViewCollectionCell?

I have a UIViewCollection with three sections, and I would like to change the background color of a UIViewCollectionCell which has a specific text. 我有一个包含三个部分的UIViewCollection,并且我想更改具有特定文本的UIViewCollectionCell的背景颜色。 For get some idea, this is what I want: 为了获得一些想法,这就是我想要的:

在此处输入图片说明

And here is my code, on Objective-C: 这是我在Objective-C上的代码:

        BOOL isExactHour = [_working_dayArray containsObject:@"07:00"];

        if (isExactHour) {
            NSInteger indexValue = [_working_dayArray indexOfObject:@"07:00"];

            NSIndexPath *path = [NSIndexPath indexPathWithIndex:indexValue];

             UICollectionViewCell *cell = [_timetablesCollection cellForItemAtIndexPath:path];

            [cell setBackgroundColor:[UIColor colorWithRed:250 green:255 blue:150 alpha:.8]];

However, if I do a NSLog, path return <NSIndexPath: 0xc00000000000000e> {length = 1, path = 0} , and the UIViewCollectionCell is still white. 但是,如果我执行NSLog,则path返回<NSIndexPath: 0xc00000000000000e> {length = 1, path = 0} ,并且UIViewCollectionCell仍为白色。

Could anyone help? 有人可以帮忙吗?

Thank you so much. 非常感谢。

You should be updating the cell during the datasource method like this. 您应该在像这样的数据源方法期间更新单元格。 Keep in mind that in order to actually color all cells that land on an exact hour, you probably need to use some other comparison besides strings like dates: 请记住,为了给所有确切在一个小时内到达的单元格着色,除了日期之类的字符串外,您可能还需要使用其他一些比较:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"mycellidentifier" forIndexPath:indexPath];
    //Grab the string from whatever internal storage you are using. This would work if you only have one section, be aware it might not be exact for your case.
    NSString *hour = [_working_dayArray objectAtIndex:indexPath.row];
    if ([hour isEqualToString:@"7:00"]) {
      //Color cell background yellow
    } else {
      //Color cell background white
    }
  return cell;
}

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

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