简体   繁体   中英

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. For get some idea, this is what I want:

在此处输入图片说明

And here is my code, on 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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