代码之家  ›  专栏  ›  技术社区  ›  Mario

访问以编程方式创建的UILabel

  •  1
  • Mario  · 技术社区  · 16 年前

    好吧,我的问题是:

    我有创建标签的功能:

    - (void)crateBall:(NSInteger *)nummer {
      UILabel *BallNummer = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
      BallNummer.text = [NSString stringWithFormat:@"%i", nummer];
      [self.view addSubview:BallNummer];
    }
    

    现在我想在另一个函数中访问标签来更改文本、帧等。

    这些标签的数量是动态的,所以我不想在.h文件中声明每个标签。

    2 回复  |  直到 14 年前
        1
  •  4
  •   Vladimir    16 年前

    所有UIView子类都有整数 tag 你的财产

    - (void)crateBall:(NSInteger *)nummer {
      UILabel *BallNummer = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
      BallNummer.text = [NSString stringWithFormat:@"%i", nummer];
      BallNummer.tag = *nummer;
      [self.view addSubview:BallNummer];
      [BallNummer release];
    }
    

    稍后您可以使用 -viewWithTag: 功能:

    UILabel *ballNummer = (UILabel*)[self.view viewWithTag:nummer];
    

    BallNummer.text = [NSString stringWithFormat:@"%i", *nummer];
    

        2
  •  0
  •   Akusete    16 年前

    你可以用 UIView '标记属性来标记子视图,并创建一个函数来访问所需的标签

    - (void)createLabels {
      UILabel *label;
    
      label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
      label.tag = 1;
      [self.view addSubview:label];
    
      label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
      label.tag = 2;
      [self.view addSubview:label];
    
      //etc...
    }
    
    -(UILabel*) getLabel:(NSInteger) index {
        return [self.view viewWithTag:index];
    }