淡出UICollectionView中的项目

我有一个UICollectionView,我正在根据这个链接实现粘性标题: http ://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using #notes

它非常有效但是我的窗口应用了背景图像,我的标题视图具有透明背景。 因此,当我的项目在标题视图上方滚动时,您仍然可以看到它们。

理想情况下,我会逐渐淡出带有渐变的单元格,直到它在标题视图后面显示时它是不可见的。

谢谢。

你还没有发布任何代码,所以这里不用看代码就可以了。 只需在UICollectionView设置一个遮罩层,你就可以了:

 CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = self.collectionView.superview.bounds; gradient.colors = @[(id)[UIColor clearColor].CGColor, (id)[UIColor blackColor].CGColor]; // Here, percentage would be the percentage of the collection view // you wish to blur from the top. This depends on the relative sizes // of your collection view and the header. gradient.locations = @[@0.0, @(percentage)]; self.collectionView.superview.layer.mask = gradient; 

要使此解决方案正常工作,您必须将集合视图嵌入到自己的超级视图中。

有关图层蒙版的更多信息,请查看文档。

我在具有这种效果的collectionview上创建了一个淡入淡出模板。 也许你正在寻找类似的东西。

在此处输入图像描述

 // This is in the UICollectionView subclass private func addGradientMask() { let coverView = GradientView(frame: self.bounds) let coverLayer = coverView.layer as! CAGradientLayer coverLayer.colors = [UIColor.whiteColor().colorWithAlphaComponent(0).CGColor, UIColor.whiteColor().CGColor, UIColor.whiteColor().colorWithAlphaComponent(0).CGColor] coverLayer.locations = [0.0, 0.5, 1.0] coverLayer.startPoint = CGPoint(x: 0.0, y: 0.5) coverLayer.endPoint = CGPoint(x: 1.0, y: 0.5) self.maskView = coverView } // Declare this anywhere outside the sublcass class GradientView: UIView { override class func layerClass() -> AnyClass { return CAGradientLayer.self } } 

此外,您可以通过将其添加到collectionview子类来使其变粘(即,它将始终淡出边缘上的单元格,而不是使用集合滚动)。

 func scrollViewDidScroll(scrollView: UIScrollView) { self.maskView?.frame = self.bounds } 

在我看来,你正在关注/使用的代码为你做了大量工作。 到目前为止,我可以看到(现在无法测试)只需传递alpha属性:

  layoutAttributes.zIndex = 1024; layoutAttributes.frame = (CGRect){ .origin = origin, .size = layoutAttributes.frame.size 

像这样

  layoutAttributes.zIndex = 1024; layoutAttributes.alpha = 0.1; //add this layoutAttributes.frame = (CGRect){ .origin = origin, .size = layoutAttributes.frame.size 

而不是在标题上有透明背景,我会创建一个渐变透明png并使用它。 使用图像处理渐变比使用代码处理梯度要高效得多。

您应该为CollectionView使用UIScrollViewDelegate ,并使用scrollviewdidscroll方法创建淡入淡出或子类UICollectionViewFlowLayout

这就是我实现这种效果的方式。 我在photoshop中创建了一个渐变图像,淡化为背景的颜色,在我的情况下是黑色的。 这是它的样子: 在此处输入图像描述

我将ImageView放在我的ViewController上。 我将它拉伸到我想要的正确大小和位置,并使用AutoLayout约束将其锁定到位。 (我不得不使用键盘上的箭头键来移动它,因为点击并拖动图像的位置往往会将其放在CollectionView内部)

单击ImageView,转到编辑器 – >排列 – >发送到前面以确保它位于CollectionView的顶部。

图像模式是Scale to Fill,我已取消选择User Interaction Enabled。

这将需要一些调整,以使一切都完美,但它工作得很好,看起来不错。

我不完全确定你的背景图像和诸如此类的意思,但可能会使渐变图像成为你拥有的实际背景图像的一部分,因此它会混合在一起。