我写了一个方法来为按钮添加圆角,渐变背景和阴影。此方法已在具有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
}
答案 0 :(得分:0)
好的我修好了。必须在viewDidAppear而不是viewDidLoad中加载该方法!现在它有效!