Objective C - UICollectionView左/右侧的渐变渐变

时间:2013-05-19 06:21:53

标签: objective-c gradient uicollectionview

我在视图控制器的主视图中有一个横向滚动的UICollectionView,就像这样(Gray是UIView,Wood是UICollectionView):

我想在最左边添加固定的褪色渐变&这个UICollectionView的最右边的sies,以便当用户滚动时滚动看起来消失。我该怎么做呢?它是否涉及使用CAGradientLayer?如果您能给我任何帮助,我将不胜感激!

2 个答案:

答案 0 :(得分:8)

由于this tutorial at cocoanetics,我实际上设法使用一个遮罩层来解决这个问题。这是我做的:

@interface ScalesViewController : UIViewController
{
    CAGradientLayer *maskLayer;
}
@end

然后在.m中,我放置了以下内容:

- (void)viewDidAppear:(BOOL)animated
{

    [super viewWillAppear: animated];

    if (!maskLayer)
    {
        maskLayer = [CAGradientLayer layer];

        CGColorRef outerColor = [[UIColor colorWithWhite:0.0 alpha:1.0] CGColor];
        CGColorRef innerColor = [[UIColor colorWithWhite:0.0 alpha:0.0] CGColor];

        maskLayer.colors = [NSArray arrayWithObjects:
                           (__bridge id)outerColor,
                           (__bridge id)innerColor,
                           (__bridge id)innerColor,
                           (__bridge id)outerColor, nil];

        maskLayer.locations = [NSArray arrayWithObjects:
                              [NSNumber numberWithFloat:0.0],
                              [NSNumber numberWithFloat:0.125],
                              [NSNumber numberWithFloat:0.875],
                              [NSNumber numberWithFloat:1.0], nil];

        [maskLayer setStartPoint:CGPointMake(0, 0.5)];
        [maskLayer setEndPoint:CGPointMake(1, 0.5)];

        maskLayer.bounds = self.mainCollectionView.bounds;
        maskLayer.anchorPoint = CGPointZero;

        [self.mainCollectionView.layer insertSublayer: maskLayer atIndex: 0];
    }
}

这会在我的集合视图的两侧创建一个漂亮的“淡黑色”效果。可以在地点和地点添加更多颜色。用于细化渐变混合的颜色属性。起点/终点确定渐变的方向和位置。

答案 1 :(得分:1)

尝试在集合视图子图层上添加两层CAGradientLayer:

#import <QuartzCore/QuartzCore.h>

CAGradientLayer *leftShadow = [CAGradientLayer layer];
leftShadow.frame = CGRectMake(0, 0, 100, self.collectionView.frame.size.height);
leftShadow.startPoint = CGPointMake(0, 0.5);
leftShadow.endPoint = CGPointMake(1.0, 0.5);
leftShadow.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.0 alpha:0.4f] CGColor], (id)[[UIColor clearColor] CGColor], nil];

[self.collectionView.layer addSublayer:leftShadow];

CAGradientLayer *rightShadow = [CAGradientLayer layer];
rightShadow.frame = CGRectMake(CGRectGetWidth(self.collectionView.frame)-100.0, 0, 100, self.collectionView.frame.size.height);
rightShadow.startPoint = CGPointMake(1.0, 0.5);
rightShadow.endPoint = CGPointMake(0, 0.5);
rightShadow.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.0 alpha:0.4f] CGColor], (id)[[UIColor clearColor] CGColor], nil];

[self.collectionView.layer addSublayer:rightShadow];