iphone - 使用渐变和阴影创建按钮的单独方法

标签 iphone ios objective-c uibutton

我写了一个给按钮添加圆角、渐变背景和阴影的方法。此方法已使用 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  
    } 

最佳答案

好的,我修好了。该方法必须在 viewDidAppear 而不是 viewDidLoad 中加载!现在可以了!

关于iphone - 使用渐变和阴影创建按钮的单独方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305422/

相关文章:

ios - Ble广告数据慢间隔时间

ios - 基于 iOS 应用程序设计 View Hierarchy Tabbar bar

iphone - 在触摸结束之前,如何在按钮的单击事件上启动事件指示器?

objective-c - 如何强制焦点更改为 tvOS 中的特定 View ?

objective-c - 我可以创建只对我的类可见的 C 函数,它被分成多个文件吗?

ios - 找不到 Cocoapods <RestKit/RestKit.h>

ios - 未捕获的异常 'InvalidPathValidation',原因 : '(child:) Must be a non-empty string and not contain ' .' ' #' ' $' ' [' or ' ]''

ios - Core Plot 中的 expandRangeByFactor 方法出错

ios - 弱属性的大量开销?

objective-c - 使用 SceneKit 渲染一个 CVOpenGLTextureRef