ios - 如何在突出显示时使图像变暗(在 Collection View 中)?

标签 ios objective-c

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

enter image description here

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

enter image description here

我尝试使用 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/

相关文章:

ios - 等待进入 Controller ,直到 wifi 启用 IOS

ios - 在 iOS 应用程序中将数据本地保存在设备上的最佳方式

ios - Xcode 10、Swift 4 - 如何跨多个 View Controller 传输数据?

ios - iOS 9.3 中的 Google+ 正在挂断

objective-c - 在没有 UIWebView 的情况下打开 URL 以在服务器上启动进程

objective-c - 按降序排列数组(NSArray)

ios - 对象如何存储在 NSData 中?数据大小(以字节为单位)是否与存储为 NSData 之前相同?

iphone - 在 iOS 中将 zip 作为附件添加到 MFMailComposeViewController 失败

ios - 意外行为播放视频在iOS 9 中使用MPMoviePlayerViewController 播放本地视频时?

ios - IOS 13.2.3版本TextField文本不显示如何解决?