4

我写了一个方法来为按钮添加圆角、渐变背景和阴影。这个方法已经用UIButton类写在单独的文件 h 和 m 中,因此可以从应用程序中的任何地方调用它。我不知道为什么,当我回忆起该方法时,按钮出现正确的阴影和圆角,但没有正确的背景渐变。我认为问题与self,即回忆方法有关:按钮属性右阴影和角,但似乎没有将渐变读取为与自身相关。有人可以帮助我吗?谢谢大家。这是代码。

-(void) makeGradient {    
    //corners this works    
    CALayer *thisLayer = self.layer;    
    // Add a border     
    thisLayer.cornerRadius = 8.0f;   
    thisLayer.masksToBounds = YES; 
    thisLayer.borderWidth = 2.0f;    
    thisLayer.borderColor = self.backgroundColor.CGColor;
    //Gradient this doesn't work
    btnGradient.cornerRadius=8.f;
CAGradientLayer *btnGradient = [CAGradientLayer layer];
btnGradient.frame = thisLayer.bounds;
       btnGradient.colors = [NSArray arrayWithObjects:
                      (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                      (id)[UIColor colorWithWhite:1.0f alpha:0.2f].CGColor,
                      (id)[UIColor colorWithWhite:0.75f alpha:0.2f].CGColor,
                      (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,
                      (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                      nil];
btnGradient.locations = [NSArray arrayWithObjects:
                         [NSNumber numberWithFloat:0.0f],
                         [NSNumber numberWithFloat:0.5f],
                         [NSNumber numberWithFloat:0.5f],
                         [NSNumber numberWithFloat:0.8f],
                         [NSNumber numberWithFloat:1.0f],
                         nil];
                       [thisLayer addSublayer:btnGradient];

    //Shadow this work

    // Give it a shadow  
    if ([thisLayer respondsToSelector:@selector(shadowOpacity)]) 
    { // For compatibility, check if shadow is supported  
        thisLayer.shadowOpacity = 0.7;  
        thisLayer.shadowColor = [[UIColor blackColor] CGColor];  
        thisLayer.shadowOffset = CGSizeMake(0.0, 3.0);  

        // TODO: Need to test these on iPad  
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2)  
        {  
            thisLayer.rasterizationScale=2.0;  
        }  
        thisLayer.shouldRasterize = YES; // FYI: Shadows have a poor effect on performance  
    } 
4

1 回答 1

0

好的,我修好了。该方法必须在 viewDidAppear 而不是 viewDidLoad 中加载!现在它起作用了!

于 2013-05-02T05:46:45.707 回答