如何更改特定 UIViewCollectionCell 的背景颜色?
How can I change the background color of an specific UIViewCollectionCell?
我有一个包含三个部分的 UIViewCollection,我想更改具有特定文本的 UIViewCollectionCell 的背景颜色。为了得到一些想法,这就是我想要的:
这是我的代码,在 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]];
但是,如果我执行 NSLog,path
return <NSIndexPath: 0xc00000000000000e> {length = 1, path = 0}
,并且 UIViewCollectionCell 仍然是白色的。
有人能帮忙吗?
非常感谢。
您应该像这样在数据源方法期间更新单元格。请记住,为了真正为所有在准确时间到达的单元格着色,您可能需要使用除日期之类的字符串之外的其他一些比较:
- (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;
}
我有一个包含三个部分的 UIViewCollection,我想更改具有特定文本的 UIViewCollectionCell 的背景颜色。为了得到一些想法,这就是我想要的:
这是我的代码,在 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]];
但是,如果我执行 NSLog,path
return <NSIndexPath: 0xc00000000000000e> {length = 1, path = 0}
,并且 UIViewCollectionCell 仍然是白色的。
有人能帮忙吗?
非常感谢。
您应该像这样在数据源方法期间更新单元格。请记住,为了真正为所有在准确时间到达的单元格着色,您可能需要使用除日期之类的字符串之外的其他一些比较:
- (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;
}