简体   繁体   English

高亮显示如何从UIButton中删除CAGradientLayer

[英]How to remove CAGradientLayer from UIButton when it's highlighted

I've added gradient effect for my Button and added it as a sub layer to my Button . 我为Button添加了渐变效果,并将其作为子层添加到Button

Code is : 代码是:

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = self.myButton.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];
self.myButton.layer.cornerRadius = 5;
gradientLayer.cornerRadius = self.myButton.layer.cornerRadius;
[self.myButton.layer addSublayer:gradientLayer];

Now when my button is highlighted (touchedDown method called), I want to set new gradient to myButton. 现在,当我的按钮突出显示时(调用touchedDown方法),我想为myButton设置新的渐变。 Hence I need to remove the old gradient effect when myButton is clicked and add new gradient. 因此,当单击myButton时,我需要删除旧的渐变效果并添加新的渐变。

How to remove the old gradient effect ? 如何去除旧的渐变效果?

I tried 我试过了

for (CALayer *layer in [self.loginScreenView.btnPowerBroking.layer.sublayers copy]){
        if ([[layer name] isEqualToString:@"gradientLayer"]) {
            NSLog(@"Gradient layer found.");
        }
    }

But I can't get it's gradient layer. 但是我不能得到它的渐变层。

Thanks for your time. 谢谢你的时间。 (: (:

You haven't set the name property to your gradientLayer object just set it and it will work. 您尚未将name属性设置为您的gradientLayer对象,只需对其进行设置即可。

 gradientLayer.name = @"gradientLayer";
 [self.myButton.layer addSublayer:gradientLayer];

In for loop's if statement remove the layer using this [layer removeFromSuperlayer]; 在for循环的if statement中,使用此[layer removeFromSuperlayer];删除该层[layer removeFromSuperlayer];

Note : You are adding layer in myButton object in searching inside the btnPowerBroking check properly for that also, you need to search in button where you have added Layer . 注意:您还需要在btnPowerBroking检查内正确搜索myButton对象中添加图层,还需要在已添加Layer按钮中搜索。

试试这个方法...

[self.myButton.layer replaceSublayer:oldgradientLayer with:newgradientLayer];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM