iphone - UIButton 渐变不起作用

标签 iphone ios objective-c cocoa uibutton

我从教程中找到了这段代码并尝试使用它:

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/

相关文章:

使用 Siri 将 iPhone 语音转为文本,反之亦然

iPhone 构建配置启用功能

iphone - NSUserDefaults 仅在首次启动时显示窗口

iphone - 发布保留 View 的最佳实践?

ios - 如何动态设置强制触摸标题

ios - NSUserDefaults 为 valueForKey 返回 null

iphone - 横向模式下的图像封面流

ios - 同时为多个 UIView 设置动画

ios - CoreData加密提交到应用商店时是否需要任何类型的额外文件

ios - UITableViewCell调整大小以适合详细文本