我从教程中找到了这段代码并尝试使用它:
CAGradientLayer *btnGradient = [CAGradientLayer layer];
btnGradient.frame = button.bounds;
btnGradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:102.0f / 255.0f green:102.0f / 255.0f blue:102.0f / 255.0f alpha:1.0f] CGColor],
(id)[[UIColor colorWithRed:51.0f / 255.0f green:51.0f / 255.0f blue:51.0f / 255.0f alpha:1.0f] CGColor],
nil];
[button.layer insertSublayer:btnGradient atIndex:0];
代码在viewDidLoad方法中。
按钮在 .h 文件中定义如下:@property (nonatomic, strong) IBOutlet UIButton *button;
它在 .m 文件中 @synthesized 并在界面生成器中连接
我可以对按钮进行其他自定义,例如更改其背景颜色(纯色)和更改文本颜色。但是当我尝试使用渐变颜色时,背景只是透明的。
我感谢您的帮助!
您需要设置渐变层的框架以覆盖整个按钮。机会是在viewDidLoad
按钮的大小为零,这使得渐变层的框架为零...并且稍后当按钮的大小改变时,渐变层的框架不会相应地改变。
子类化UIButton
并压倒一切layoutSubviews
是个好主意
@interface MyButton : UIButton {
}
@implementation MyButton {
CAGradientLayer* _gradient;
}
-(id)init {
self = [super init];
_gradient = [CAGradientLayer layer];
_gradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:102.0f / 255.0f green:102.0f / 255.0f blue:102.0f / 255.0f alpha:1.0f] CGColor],
(id)[[UIColor colorWithRed:51.0f / 255.0f green:51.0f / 255.0f blue:51.0f / 255.0f alpha:1.0f] CGColor],
nil];
[self.layer insertSublayer:_gradient atIndex:0];
}
-(void)layoutSubviews {
[super layoutSubviews];
_gradient.frame = self.bounds;
}
@end
另一种选择是使用observeValueForKeyPath...
检测按钮框架的变化,并相应地调整图层大小。不是一个非常可重用的解决方案思想。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)