replaceSublayer example

浪子不回头ぞ 提交于 2019-12-08 07:00:46

问题


I have the following code and I can't seem to get it to work.

First I create a view with a layer.

UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];

Next I need to replace that layer. I have tried the following and it fails because I don't know how to access that layer 0. At this point I am in a different part of the program so I cannot just call gradient. I need to extricate it from view somehow.

[view.layer replaceSublayer:0 with:newgradient];

Apparently the 0 is supposed to be Old layer but I don't know how to access it.

Thanks.


回答1:


I think you should be able to use this:

[view.layer replaceSublayer:[[view.layer sublayers] objectAtIndex:0]
            with:newGradient];

I'm away from my Xcode development environment and can't test this at the moment though.




回答2:


Keep a pointer to the gradient layer. If you have alot of them do it with an array. If you still don't want to do that you can always use this to get an array of all the layers..

[self.layer sublayers];

Then you can cycle through and check some parameter to see if they are the same. Like set the layer.name to something when you create it.




回答3:


Here is the function :

#define MyGradientLayerName @"MyGradient"

void makeViewGradient(UIView *pView,BOOL bRemoveBackground,CGColorRef clr1,CGColorRef clr2)
{
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.name = MyGradientLayerName;

    gradient.frame = pView.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)clr1,(id)clr2,nil];

    CALayer *pGradientLayer = nil;
    NSArray *ar = pView.layer.sublayers;
    for (CALayer *pLayer in ar)
    {
        if ([pLayer.name isEqualToString:MyGradientLayerName])
        {
            pGradientLayer = pLayer;
            break;
        }
    }
    if (!pGradientLayer) [pView.layer insertSublayer:gradient atIndex:0];
    else [pView.layer replaceSublayer:pGradientLayer with:gradient];

    if (bRemoveBackground) pView.backgroundColor = nil;//free memory !
}


来源:https://stackoverflow.com/questions/3713292/replacesublayer-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!