我想实现在CollectionView中单击单元格时可以变成红色的效果,所以我使用了CAlayer,但它不起作用。当我使用target-action在单元内部实现时,它可以完美地工作。代码如下:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
videoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"videoCell" forIndexPath:indexPath];
CALayer *testLayer = [[CALayer layer] init];
testLayer.frame = cell.bounds;
testLayer.backgroundColor = [UIColor redColor].CGColor;
[cell.layer addSublayer:testLayer];
}发布于 2021-01-05 16:49:26
您需要使用单元的contentView来完成此操作。此外,请记住,单元格是缓存,因此您不能使用存储在单元格中的状态。你得把它放在别的地方。并且您不应该使用didSelectItemAtIndexPath来更新UI。而是更改那里的状态,然后请求并更新相关单元。
这里有一个很好的例子来说明。在此示例中,您可以选择多个单元格,它们都将具有红色背景。单元格的选择状态存储在控制器的字典中。如果你只想在给定的时刻选择一个单元格,你可以很容易地改变这一点。然后,您还需要更新变为未选中的单元格,但这是另一个示例。
#import "CollectionViewController.h"
@interface CollectionViewController () < UICollectionViewDelegate, UICollectionViewDataSource >
@property (nonatomic,strong) NSMutableDictionary * selectedCells; // Key is integer row, value is boolean selected
@end
@implementation CollectionViewController
static NSString * const reuseIdentifier = @"Cell";
- (void)viewDidLoad {
[super viewDidLoad];
// Register cell classes
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
// Do any additional setup after loading the view.
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
// Empty / nothing selected for now
self.selectedCells = NSMutableDictionary.dictionary;
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 5;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
// Configure the cell based on state
if ( [( NSNumber * )[self.selectedCells objectForKey:@( indexPath.row )] boolValue] ) {
cell.contentView.backgroundColor = UIColor.redColor;
} else {
cell.contentView.backgroundColor = UIColor.blueColor;
}
return cell;
}
#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
// Flip selected state
[self.selectedCells setObject:@( ! [( NSNumber * )[self.selectedCells objectForKey:@( indexPath.row )] boolValue] )
forKey:@( indexPath.row )];
// Request an UI update to reflect the updated state
[collectionView reloadItemsAtIndexPaths:@[ indexPath ]];
}
@endhttps://stackoverflow.com/questions/65575003
复制相似问题