views:

92

answers:

2

Ok my problem:

I have function to create a Label:

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

Now i wanna access the label in a other function to change text, frame ect.

The number of these labels is dynamic so i don't wanna declare each one in the .h file. (i dont mean the number .text = 123 i mean the number of labels in the view)

I hope you understand my English. Thanks for Help :D

Greetings from Switzerland!

+3  A: 

All UIView subclasses have integer tag property for your purpose

- (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];
}

Later you can get this label using -viewWithTag: function:

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

P.S. as you pass pointer to int to your function (do you really need to do so?) you should dereference it before using its value:

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

P.P.S. Do not forget to release label your create (I've added release to my code) - your code leaks memory

Vladimir
Thank you, a typo )
Vladimir
Thank you very very much this works fine :D
Mario
A: 

You can use UIView' tag property to label your subviews, and create a single function to access the label you are after

- (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];
}
Akusete