簡體   English   中英

從ios中的視圖中計算和刪除子視圖

[英]Count and remove Subviews from view in ios

這是我創建子視圖並將其添加到視圖中的方式。

我想知道為什么計數總是返回0,它應該返回“數百”。 我做錯了什么,謝謝!

我添加了更多代碼,清楚地顯示了我的問題。 我復制/粘貼了我最初問題涉及的所有功能。

    - (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); 

}

以下是我的一些想法:

  1. 我會檢查self.vistaPanelBotones是否為非零,以防萬一(如果它是零,你不會在該代碼中得到任何錯誤,但也沒有子視圖)。
  2. 在擁有有效幀之前可能執行此操作(IIRC,viewWillAppear是具有有效幾何的最早回調)
  3. 我很確定如果boton是零,你在添加為子視圖時會遇到異常,但這是另一個值得用於調試的測試。

使用[[self.vistaPanelBotones subviews] count]計算子視圖的數量,但是有一種優雅的方法可以從Objective-C中的視圖中刪除所有子視圖。 嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM