0

我创建了一个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];

}

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

4

1 回答 1

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
于 2014-04-24T20:21:39.157 回答