将CAGradientLayer子图层添加到UIView的问题

时间:2014-04-24 20:08:12

标签: ios uiview cagradientlayer

我已经创建了CAGradientLayer,我想将其添加为UIView的子图层。我可以毫无问题地将其添加到self.view.layer,但在我的生活中不能将其添加到UIView时显示。

这是简化代码。

- (CAGradientLayer*) makeGradient 
{

    //method returns the gradient layer

    CAGradientLayer *gradeLayer = [CAGradientLayer layer];
    gradeLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
    gradeLayer.locations =  [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.2], [NSNumber numberWithFloat:0.5], nil];

    return gradeLayer;
}


-(void)addGradient
{

    //method creates UIView, then creates Gradient, and tries to add it to the UIView

    UIView *myView = [[UIView alloc] initWithFrame:self.view.frame];
    myView.backgroundColor = [UIColor clearColor];
    myView.opaque = NO;

    CAGradientLayer *bg = [self makeGradient];
    CGRect myRect = myView.bounds;
    myRect.size.height = myRect.size.height * 5;
    myRect.origin.y = myView.bounds.size.height-myRect.size.height;

    bg.frame = myRect;

    //Adding gradient to self.view.layer works like a charm...
    //[self.view.layer insertSublayer:bg atIndex:0];

    //...however, adding it to my custom view doesn't work at all.
    [myView.layer insertSublayer:bg atIndex:0];

}

我错过了什么?提前感谢任何见解。

1 个答案:

答案 0 :(得分:0)

您的问题是您似乎没有在子图层上设置框架。相反,更清晰的选择是子类UIView并使用layerClass

<强> CustomGradientView.h

// For CALayers, make sure you also add the QuartzCore framework
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CustomGradientView : UIView

// Redeclare the layer property but as the new CALayer class so it can receive the correct
// messages without compiler warnings.
@property (nonatomic, strong, readonly) CAGradientLayer *layer;

@end

<强> CustomGradientView.m

#import "CustomGradientView.h"

@interface CustomGradientView ()

@end

@implementation CustomGradientView

+(Class)layerClass
{
    return [CAGradientLayer class];
}

-(instancetype)init
{
    self = [super init];
    if (self) {
        [self customInit];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)decoder
{
    self = [super initWithCoder:decoder];
    if (self) {
        [self customInit];
    }
    return self;
}

-(void)customInit
{
    self.layer.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
    self.layer.locations =  [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.2], [NSNumber numberWithFloat:0.5], nil];
}

@end