我正在尝试根据条件预先选择一些单元格,这些单元格设置选定的单元格,并在绘制这些单元格时更改其背景颜色。现在方法
didSelectItemAtIndexPath / didDeselectItemAtIndexPath
不会仅为那些preselected
单元格调用,因此我无法切换选择和background color
。正在为其他单元格调用select/deselect delegate methods
-(UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"cellForItemAtIndexPath: %@", indexPath);
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell" forIndexPath:indexPath];
if(indexPath.row != 0 && indexPath.row != 8 && indexPath.section != 0 && indexPath.section != 25){
NSMutableDictionary *blockedHours = [blockedDaysArray objectAtIndex:indexPath.row-1];
NSString *blockedVal = [blockedHours valueForKey:@(indexPath.section-1).stringValue];
[cell setBlockedVal:(NSString*)blockedVal];
}
[cell addDayTimeLable:indexPath];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"didSelectItemAtIndexPath: %@ ", indexPath);
NSMutableDictionary *blockedHours = [blockedDaysArray objectAtIndex:indexPath.row-1];
[blockedHours setValue:@"1" forKey:@(indexPath.section-1).stringValue];
CollectionViewCell *cell = (CollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
cell.selected = YES;
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"didDeselectItemAtIndexPath %@", indexPath);
NSMutableDictionary *blockedHours = [blockedDaysArray objectAtIndex:indexPath.row-1];
[blockedHours setValue:@"0" forKey:@(indexPath.section-1).stringValue];
CollectionViewCell *cell = (CollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
cell.selected = NO;
}
在CollectionViewCell.m中:
Self.selected调用setter方法,因此chagnes背景颜色
-(void)setBlockedVal:(NSString*)blockedVal{
if([blockedVal isEqualToString:@"1"]){
self.selected = YES;
}
}
-(void)setSelected:(BOOL)selected{
NSLog(@"set selected: %d", selected);
[super setSelected:selected];
if(selected)
self.backgroundColor = [SFIColors lightGreenColor];
else
self.backgroundColor = [UIColor whiteColor];
}
注意:
(1)didHighlightItemAtIndexPath / didUnHighlightItemAtIndexPath是 被要求预选的细胞。
(2)我刚发现通过didselect / didunselect选择的设置是 多余的,我刚从我的代码中删除。注意到setSeleted是 自动调用单击其他单元格。仍然这个setSelected不是 适用于预选细胞
任何输入来修复这个或我可以完成任务的其他方式都会有很大的帮助。
答案 0 :(得分:0)
我在此链接中找到了答案:UICollectionView - didDeselectItemAtIndexPath not called if cell is selected
实际上我实际上搜索了很多,但直到现在我才找到了这个链接。我让我的收藏视图知道我的选择,这就是诀窍:
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];