我知道如果我们在将渐变分配给按钮作为子图层后添加标题,按钮的标题将在前面。
但这种情况有所不同。
我正在改变正常状态的渐变并触发按钮的状态。
这是我的代码:
-(void) buttonClicked:(UIButton*)sender{
sender.backgroundColor = [UIColor clearColor];
// Finding old gradient layer to remove it
for (CALayer *layer in [sender.layer.sublayers copy]){
if ([[layer name] isEqualToString:@"gradientLayer"]) {
[layer removeFromSuperlayer];
}
}
// Applying the new gradient
UIColor *colorTwo = [UIColor colorWithRed:1.00 green:0.81 blue:0.00 alpha:0.95]; // Original
UIColor *colorThree = [[UIColor brownColor] colorWithAlphaComponent:1];
UIColor *colorFour = [[UIColor blackColor] colorWithAlphaComponent:0.9];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = sender.layer.bounds;
gradientLayer.colors = [NSArray arrayWithObjects: (id)[[UIColor whiteColor] colorWithAlphaComponent:0.5].CGColor,(id) colorTwo.CGColor,(id) colorThree.CGColor,(id) colorFour.CGColor, nil];
gradientLayer.locations = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:1.0f], nil];
sender.layer.cornerRadius = 5;
gradientLayer.cornerRadius = sender.layer.cornerRadius;
// Adding gradient
[sender.layer addSublayer:gradientLayer];
gradientLayer.name = @"gradientLayer";
// Adding title after applying the gradient ( BUT ALSO TITLE IS GOING BEHIND THE GRADIENT )
sender.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
sender.titleLabel.numberOfLines = 2;
NSString *str = sender.titleLabel.text;
[sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[sender setTitle:str forState:UIControlStateNormal];
}
-(void) touchedDown:(UIButton*)sender{
// Finding old gradient layer to remove it
for (CALayer *layer in [sender.layer.sublayers copy]){
if ([[layer name] isEqualToString:@"gradientLayer"]) {
[layer removeFromSuperlayer];
}
}
// Applying the new gradient
CAGradientLayer *gradientLayer1 = [CAGradientLayer layer];
gradientLayer1.frame = sender.layer.bounds;
gradientLayer1.colors = [NSArray arrayWithObjects: (id)[[UIColor whiteColor] colorWithAlphaComponent:0.5].CGColor, (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,(id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor, nil];
gradientLayer1.locations = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:1.0f], nil];
gradientLayer1.cornerRadius = sender.layer.cornerRadius;
// Adding Gradient
[sender.layer addSublayer:gradientLayer1];
gradientLayer1.name = @"gradientLayer";
sender.backgroundColor = [UIColor blackColor];
[sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
第一次启动应用程序时,标题就在前面。但是当我开始点击它时,标题就会落在渐变之后。请帮我解决这个问题。谢谢你的时间(:
答案 0 :(得分:4)
问题在于这一行:
[sender.layer addSublayer:gradientLayer];
这意味着:在所有其他子图层前添加渐变图层 。这包括显示标题标签的图层。
相反,请致电insertSublayer:atIndex:
(或above:
或below:
),将图层放置在您想要的其他图层中。
但是,最好不要直接弄乱按钮的图层。不是将渐变应用为图层,而是将渐变(在代码中)绘制到图像中,并将该图像用作按钮的背景图像。
此外,您可以配置背景图像,以便在用户点击按钮时自动更改 。