如何删除或隐藏子图层?

时间:2013-12-03 10:53:45

标签: objective-c calayer

-(IBAction)displayinfo:(id)sender
{
    sublayer = [CALayer layer];

    if (appear == NO)
    {
        appear = YES;
        sublayer.contents=(id)[UIImage imageNamed:@"infoPalette.png"].CGImage;
        sublayer.frame= CGRectMake(300,200,350,250);
        [self.view.layer addSublayer:sublayer];
    }
    else
    {
        [sublayer removeFromSuperlayer];
    }
}

这允许图层出现但我无法删除它或在单击相同的按钮时隐藏它。

3 个答案:

答案 0 :(得分:11)

用这个替换现有代码

-(IBAction)displayinfo:(id)sender
{

    if ( appear == NO)
    {
         sublayer = [CALayer layer];
         appear = YES;
         sublayer.contents=(id)[UIImage imageNamed:@"infoPalette.png"].CGImage;
         sublayer.frame= CGRectMake(300,200,350,250);
         [self.view.layer addSublayer:sublayer];
    }
    else
    {
        [sublayer removeFromSuperlayer];
    }
}

答案 1 :(得分:5)

在我的情况下,我在背景imageView中添加了多个子图层,我使用

删除了所有子图层
 for (int i = 0 ; i < [self.backgroundImageView.layer.sublayers count]; i++ ) {
        [[self.backgroundImageView.layer.sublayers objectAtIndex:i] removeFromSuperlayer];
    }

注意:我也像这样迭代

 for (CALayer *layer in self.backgroundImageView.layer.sublayers) {
      [layer removeFromSuperlayer];
 }

但这会导致BadAccess,这可能就是我将一些CAGradientLayer添加到backgroundImageView.Layer的原因。 (虽然没有多大意义)。

答案 2 :(得分:0)

您将代码更改为

- (IBAction)displayinfo:(id)sender{
if (appear == NO){
    sublayer = [CALayer layer];
    appear = YES;
    sublayer.contents=(id)[UIImage imageNamed:@"infoPalette.png"].CGImage;
    sublayer.frame= CGRectMake(300,200,350,250);
    [self.view.layer addSublayer:sublayer];
}
else {
    [sublayer removeFromSuperlayer];
}}

抱歉!,重复解决方案