我正在尝试对我的 iOS 应用程序中的所有按钮应用一个小的渐变。我为 UIButton 创建了一个类别,我在其中添加了这个功能,它基本上为按钮添加了字幕、边框和渐变层。
该函数在加载 View 时被调用:
- (void)viewDidLoad
{
[super viewDidLoad];
[_myButton buttonWithSubtitle:@"test subtitle"];
}
和分类函数
- (void)buttonWithSubtitle:(NSString*)subtitleText
{
UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(80, 20, 100, 30)];
[subTitle setText:subtitleText];
[subTitle setTextColor:[UIColor colorWithRed:(144.0 / 255.0) green:(144.0 / 255.0) blue:(144.0 / 255.0) alpha:1.0]];
[subTitle setBackgroundColor:[UIColor clearColor]];
[subTitle setFont:[UIFont fontWithName:@"American Typewriter" size:12]];
[self.titleLabel setFrame:CGRectMake(30, 20, 100, 30)];
[self setTitle:@"Main title" forState:UIControlStateNormal];
[self addSubview:subTitle];
CAGradientLayer *btnGradient = [CAGradientLayer layer];
btnGradient.frame = self.bounds;
btnGradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:255.0f / 255.0f green:255.0f / 255.0f blue:255.0f / 255.0f alpha:1.0f] CGColor],
(id)[[UIColor colorWithRed:234.0f / 255.0f green:234.0f / 255.0f blue:234.0f / 255.0f alpha:1.0f] CGColor],
nil];
[self.layer setMasksToBounds:YES];
[self.layer setCornerRadius:5.0f];
[self.layer setBorderWidth:0.8f];
[self.layer setBorderColor:[[UIColor colorWithRed:200.0f / 255.0f green:200.0f / 255.0f blue:200.0f / 255.0f alpha:1.0f] CGColor]];
[self.layer insertSublayer:btnGradient atIndex:0];
}
我的问题是,当调用上述函数时,渐变清晰可见并且按钮具有所需的设计。但是,我也有一个没有字幕的按钮类型,我使用下面的其他类别功能设置了它。
- (void)defaultButton
{
CAGradientLayer *btnGradient = [CAGradientLayer layer];
btnGradient.frame = self.bounds;
btnGradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:255.0f / 255.0f green:255.0f / 255.0f blue:255.0f / 255.0f alpha:1.0f] CGColor],
(id)[[UIColor colorWithRed:234.0f / 255.0f green:234.0f / 255.0f blue:234.0f / 255.0f alpha:1.0f] CGColor],
nil];
[self.layer setMasksToBounds:YES];
[self.layer setCornerRadius:5.0f];
[self.layer setBorderWidth:0.8f];
[self.layer setBorderColor:[[UIColor colorWithRed:200.0f / 255.0f green:200.0f / 255.0f blue:200.0f / 255.0f alpha:1.0f] CGColor]];
[self.layer insertSublayer:btnGradient atIndex:0];
}
像以前一样使用在 viewdidload 中调用的这个函数会导致按钮完全没有渐变或背景(按钮具有清晰的背景颜色。我可以通过按钮看到我的 View Controller 的 View 背景)。
- (void)viewDidLoad
{
[super viewDidLoad];
[_myButton defaultButton];
}
我所有的按钮都设置为带有图像和默认标题的自定义按钮。感谢您的帮助
最佳答案
找到了问题,虽然我不知道为什么带有字幕的代码可以工作,但问题是,启用自动布局后,您的按钮在 viewDidLoad 方法期间还没有框架。
渐变必须稍后在方法中有按钮层时应用
viewDidLayoutSubviews
参见:Can't do custom UIButton in iOS6 with enabled storyboard autolayout
关于ios - UIButton 上奇怪的 CAGradientLayer 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024150/