4

I wrote a method to add rounded corners, gradient background and shadow to buttons. This method has been written in separate files h and m with UIButton class, thus it can be recalled from everywhere within the app. I cannot figure out why, when I recall the method, the buttons appear with correct shadow and rounded corner but without the correct background gradient. I think the problem is related to the self, that is recalling the method: the button attributes right shadow and corners but it seems not to read the gradient as related to itself. Someone can help me? Thank you everyone. This the code.

-(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