WebOrCode
WebOrCode

Reputation: 7302

How to access all labels in my view controller programmatically

I am not sure is this even possible, but I will ask anyway.

This is my ViewController.h

@interface TBL_GameViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *roundText;
@property (strong, nonatomic) IBOutlet UILabel *roundNumber;

@property (strong, nonatomic) IBOutlet UILabel *playerText;
@property (strong, nonatomic) IBOutlet UILabel *playerScore;

@property (strong, nonatomic) IBOutlet UILabel *computerText;
@property (strong, nonatomic) IBOutlet UILabel *computerScore;

@end

And this is one method from .m file

- (void) lablesHiden:(BOOL)on
{
    self.roundText.hidden   = on;
    self.roundNumber.hidden = on;

    self.playerText.hidden  = on;
    self.playerScore.hidden = on;

    self.computerText.hidden  = on;
    self.computerScore.hidden = on;
}

All this is working file.

Question
is the some way to a access all available labels in my view controller programmatically ?

Reason why I am asking this is:
I will have around 10 methods that will need access these labels, to change various properties (color, text, ...).
If tomorrow I add more label, I will also need add new label to all those methods and I would like to avoid that ?

UPDATE
I the end I used this approach

- (NSArray*) getAllLabels
{

    NSArray *labels = [[NSArray alloc] initWithObjects:self.roundText, self.roundNumber, self.playerText, self.playerScore, self.computerText, self.computerScore, nil];

    return labels;
}

- (void) appear:(BOOL)on
{
    for (UILabel *label in [self getAllLabels]) {
        label.alpha = 0.0;
    }
    // more code 
}

Upvotes: 1

Views: 2605

Answers (2)

Mundi
Mundi

Reputation: 80271

You get more granular control about which labels to address by using tags. This is also cleaner than doing class introspection.

For example:

#define kPlayer 100
#define kRound  200
#define kComputer 300

#define kText 10
#define kNumber 20

You assign tags e.g. in viewDidLoad like this:

roundText.tag = kRound + kText;

Now there is no need to iterate through all subviews (you just have one iteration per transaction).

for (int x = 100; x < 400; x += 100) {
   for (int y = 10; y < 30; y += 10) {
      UILabel *label = (UILabel*) [self.view viewWithTag:x+y];
      // do something with label
   }
}

You can see that you can very conveniently exclude certain labels if you need to.

Also, via KVC, all labels can be accessed like this:

[self.view.subviews filteredArrayUsingPredicate:
  [NSPredicate predicateWithFormat:@"tag > 99"]];

Upvotes: 3

Oxcug
Oxcug

Reputation: 6604

There absolutely is a way:

for (id label in self.view.subviews) {
    if ([label isKindOfClass:[UILabel class]]) {
        // do your stuff...
    }
}

Upvotes: 5

Related Questions