我使用以下代码在UICollectionView上绘制了渐变背景图层。
CAGradientLayer* collectionRadient = [CAGradientLayer layer];
collectionRadient.bounds = self.collectionView.bounds;
collectionRadient.anchorPoint = CGPointZero;
collectionRadient.colors = [NSArray arrayWithObjects:(id)[startColor CGColor],(id)[endColor CGColor], nil];
UIView* vv = [[UIView alloc] init];
self.collectionView.backgroundView = vv;
[self.collectionView.backgroundView.layer insertSublayer:collectionRadient atIndex:0];
适用于iPhone模拟器。但不是iPad。 下图是那个。背景图层只占用UICollectionView的一部分。
答案 0 :(得分:1)
我建议创建一个名为GradientView的UIView子类或类似的东西,用作背景视图。
在GradientView的实现中,您只需要重载以下类方法:
+ (Class)layerClass
{
return [CAGradientLayer class];
}
然后,将上面的代码更改为以下内容:
UIView* backgroundView = [[GradientView alloc] initWithFrame:self.collectionView.bounds];
backgroundView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.collectionView.backgroundView = backgroundView;
CAGradientLayer* collectionGradient = (CAGradientLayer *)backgroundView.layer;
collectionGradient.anchorPoint = CGPointZero;
collectionGradient.colors = [NSArray arrayWithObjects:(id)[startColor CGColor],(id) [endColor CGColor], nil];
我希望您的自定义GradientView图层会自动调整大小。如果没有,您可能需要在自定义GradientView中实现layoutSubviews方法以调整渐变图层的大小。