如何在高亮显示时使图像变暗(在集合视图中)?

时间:2015-06-25 11:07:53

标签: ios objective-c

我有一个CollectionView,我在其中显示我的自定义CollectionViewCell,它包含一个UIImageView(称为“thumbnailView”)。

enter image description here

我想要的是是当用户按下其中一个收集单元格时,图像会变暗(与所有应用程序的iPhone主菜单中的行为完全相同)。

enter image description here

我已经尝试过使用Quartz Framework并在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];

    }
}

但它只是在收集单元格中为我的图像添加了黑角,但没有像我想要的那样使它们变暗。

1 个答案:

答案 0 :(得分:2)

您可以添加其他视图以进行突出显示。

在自定义单元格中添加属性:

@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中覆盖突出显示方法并更改单元格突出显示视图的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;
    }];
}
相关问题