Iphone 使用渐变和阴影创建按钮的单独方法
我写了一个方法来添加圆角,渐变背景和阴影按钮。此方法已使用Iphone 使用渐变和阴影创建按钮的单独方法,iphone,ios,objective-c,uibutton,Iphone,Ios,Objective C,Uibutton,我写了一个方法来添加圆角,渐变背景和阴影按钮。此方法已使用UIButton类编写在单独的文件h和m中,因此可以从应用程序中的任何地方调用它。我不明白为什么,当我回忆起这个方法时,按钮显示正确的阴影和圆角,但没有正确的背景渐变。我认为问题与self有关,即回忆方法:按钮属性为右阴影和角,但它似乎无法读取与其自身相关的渐变。有人能帮我吗?谢谢大家。这就是代码 -(void) makeGradient { //corners this works CALayer *th
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
}
好的,我修好了。该方法必须在ViewDidDisplay中加载,而不是在viewDidLoad中加载!现在它工作了 “btnGradient”是如何定义的以及在哪里定义的?对不起,我错过了一些代码。你的CALayer隐藏了背景层,不添加CALayer并查看输出我尝试了,我只留下了渐变的代码,但什么都没有发生,按钮保持其原始颜色,没有渐变