我正在尝试对我的 ios 应用程序中的所有按钮应用一个小渐变。我为 UIButton 创建了一个类别,在其中添加了这个函数,它基本上为按钮添加了字幕、边框和渐变层。
该函数在视图中调用确实加载:
- (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 中调用的这个函数会导致按钮完全没有渐变或背景(按钮有清晰的背景颜色。我可以通过按钮看到我的视图控制器的视图背景)。
- (void)viewDidLoad
{
[super viewDidLoad];
[_myButton defaultButton];
}
我所有的按钮都设置为带有图像和默认标题的自定义按钮。谢谢你的帮助