sam80
sam80

Reputation: 83

Count and remove Subviews from view in ios

this is the way I create and add subviews into a view.

I'm wondering why the count always returns 0, when it should return "hundreds". What am I doing wrong, thanks!

I have added more code where shows clearly my issue. I copy/pasted all functions involved on my initial question.

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];

        [self.contenedor addSubview:vistaPanelBotones];
        [self crearBotones];
    }

    - (void) crearBotones {
    UIColor *colores[] = {
        [UIColor blueColor],
        [UIColor brownColor],
        [UIColor redColor],
        [UIColor orangeColor],
        [UIColor greenColor],     
        [UIColor yellowColor],
        [UIColor purpleColor],
        [UIColor blackColor],
        [UIColor whiteColor],
        [UIColor darkGrayColor],
        [UIColor magentaColor],
        [UIColor cyanColor],
    };

    int indice = 0;
    for (int col = 0; col < self.vistaPanelBotones.frame.size.width ; col=col+20) {
        for (int fila = 0; fila < self.vistaPanelBotones.frame.size.height-20 ; fila = fila+20) {

            CGRect frame = CGRectMake(col, fila, 20, 20);

            Boton *boton = [Boton new];
            boton.frame = frame;
            boton.layer.backgroundColor = colores[(fila + col) % 7].CGColor;
            boton.layer.cornerRadius = 0.25;
            boton.layer.borderWidth = 0.25;
            boton.layer.borderColor = [UIColor whiteColor].CGColor;
            boton.layer.delegate = self;
            [self.vistaPanelBotones addSubview:boton];
            [boton setNeedsDisplay];    
        }
        indice++;
    }   
    NSLog(@"Vista Botones SubViews:%i",[[self.vistaPanelBotones subviews] count]); 

}

- (IBAction)reiniciar:(id)sender {

    if (self.vistaPanelBotones == nil){
        NSLog(@"no existe la vista"); 
    }
    NSUInteger count = self.vistaPanelBotones.subviews.count;
    NSLog(@"Vista SubViews: %i",count); 

}

Upvotes: 0

Views: 394

Answers (2)

Chris Trahey
Chris Trahey

Reputation: 18290

Here are a few of my thoughts:

  1. I would check if self.vistaPanelBotones is non-nil, just in case (if it were nil, you would not get any errors in that code, but also no subviews).
  2. Possibly executing this before you have a valid frame (IIRC, viewWillAppear is the earliest callback with valid geometry)
  3. I'm pretty sure if boton was nil you would get an exception when adding as a subview, but it's another test worth using for debugging.

Upvotes: 1

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

Use [[self.vistaPanelBotones subviews] count] to count the number of subviews, but there is an elegant way to remove all subviews from a view in Objective-C. Try this:

 [[self.vistaPanelBotones subviews] makeObjectsPerformSelector:@selector(removeFromSuperView];

Upvotes: 1

Related Questions