选中时突出显示收集单元格
我想突出显示UICollectionView中带有黄色边框的选定集合单元格,以便用户可以看到当前选中的单元格。我尝试这样做:选中时突出显示收集单元格
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
FilterCell *filterCell = (FilterCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"FilterCell" forIndexPath:indexPath];
filterCell.window.backgroundColor = [UIColor yellowColor];
filterCell.backgroundColor = [UIColor yellowColor];
NSLog(@"hello");
}
大约有2个UIImageView的空像素内UICollectionViewCell所以它应该工作,但事实并非如此。
它正在记录“你好”,但边界保持黑色。看到这个截图:
你所得到的细胞以错误的方式
FilterCell *filterCell = (FilterCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"FilterCell" forIndexPath:indexPath];
将出列,这是不正确的使用现在的小区或分配一个新的用指定的标识符。
使用
FilterCell *filterCell = (FilterCell *)[collectionView cellForItemAtIndexPath:indexPath];
代替。
反正一个清洁的解决方案是设置该单元的backgroundView
和selectedBackgroundView
性能,而不触及backgroundProperty
色(即会留clear
作为默认值)。通过这种方式,您可以避免委托方法并实现相同的行为。
做一个reloadItemsAtIndexPaths
:在那里,然后在cellForItemAtIndexPath,检查是否[[collectionView indexPathsForSelectedItems] containsObject:indexPath]
如果为true,那么在那里更改单元格的属性。
嗨,为可见细胞做这项工作吗?如果单元格可见,我试图分配一个图像: if([[collectionView indexPathsForVisibleItems] containsObject:indexPath]){ imageView.image = [gridImages objectAtIndex:indexPath.row]; } 但它不工作。这种情况从来都不是真的。 – 2013-07-11 10:58:57
它应该适用于任何选择。 NSLog将您的indexPath和indexPathsForVisibleItems(都可以在格式字符串中用%@看到)。 – danh 2013-07-11 14:04:17
这可能会帮助您:
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"YOUR_FILE_NAME.png"]];
- 这个代码可以帮助你改变所选单元格
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvCell" forIndexPath:indexPath];
if (cell.selected) {
cell.backgroundColor = [UIColor blueColor]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}
HMM的背景色。这是一个很好的答案。我无法决定我是否喜欢它比我的更好。将有兴趣看看别人的想法。在我最后的收集视图中,我改变了选定单元的大小,这有利于我的方法,我认为;另一方面,这个想法更直接,更直接地涉及OP的问题。 – danh 2013-04-07 18:33:46
如果您更改单元格的大小,则会调整'backgroundView'和'selectedBackgroundView'的大小。在统一的颜色背景视图的情况下,这种方法一切都很好;) – 2013-04-07 18:36:24
是啊?我相信。 +1。 :-) – danh 2013-04-07 18:38:12