我从教程中找到了这段代码并尝试使用它:
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方法中。
button 在 .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...
来检测按钮框架的变化,并相应地调整层的大小。不是一个可重用的解决方案。
关于iphone - UIButton 渐变不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477544/