我有一个 CollectionView,我在其中显示我的自定义 CollectionViewCell,它由一个 UIImageView(称为“thumbnailView”)组成。
我想要的是,当用户按下其中一个收集单元格时,图像会变暗(与所有应用程序在 iPhone 主菜单中的行为完全相同)。
我尝试使用 Quartz 框架并在 MyCustomCollectionViewCell.m 中这样做:
-(void) setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
[self setNeedsDisplay];
}
-(void) drawRect:(CGRect)rect {
[super drawRect:rect];
if (self.highlighted) {
[self.thumbnailView.layer setBackgroundColor:[UIColor blackColor].CGColor];
[self.thumbnailView.layer setOpacity:0.9];
}
}
但它只是为我在收集单元格中的图像添加了黑角,但没有像我想要的那样使它们变暗。
最佳答案
您可以添加另一个 View 来突出显示。
在自定义单元格中添加一个属性:
@property (nonatomic, strong) UIView *highlightView;
初始化并将其添加到单元格的contentView
。请注意,alpha 最初设置为零:
self.highlightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
self.highlightView.backgroundColor = [UIColor blackColor];
self.highlightView.alpha = 0;
[self.contentView addSubview:self.highlightView];
在您的自定义 UICollectionView
中覆盖高亮方法并更改单元格高亮 View 的 alpha:
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomCollectionViewCell* cell = (MyCustomCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
[UIView animateWithDuration:0.3 animations:^()
{
cell.highlightView.alpha = 0.5;
}];
}
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomCollectionViewCell* cell = (MyCustomCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
[UIView animateWithDuration:0.3 animations:^()
{
cell.highlightView.alpha = 0;
}];
}
关于ios - 如何在突出显示时使图像变暗(在 Collection View 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31048636/