Jezen Thomas
Jezen Thomas

Reputation: 13800

Looping through objects in Objective-C

I have a number of UIButtons and I'm setting a custom font on them programmatically, like this:

Button1.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button2.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button3.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button4.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button5.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button6.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];

This code is correct and it works, but it doesn't seem like the leanest way of writing it. Is there a way to loop through these elements instead?

I had imagined something like this:

for (int i = 1; i <= 5; i++) {
    Button(i).titleLabel.font = etc.. // How would I get the value of 'i'?
}

Or is this simply a bad idea?

Upvotes: 0

Views: 3243

Answers (4)

Nick
Nick

Reputation: 923

How about this? currentView is the UIView that has all the buttons in it.

NSArray* buttonsArray = currentView.subviews;

for((UIButton*) button in buttonsArray)
{
     button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}

Upvotes: 0

Artur Gurgul
Artur Gurgul

Reputation: 396

you can do like this:

NSMutableArray *buttons = [NSMutableArray array];
[buttons addObject: Button1];
[buttons addObject: Button2];
[buttons addObject: Button3];
[buttons addObject: Button4];
[buttons addObject: Button5];
[buttons addObject: Button6];

for (UIButton *button in buttons) {
    button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}

or

for (int i=1;i<7;i++) {
    SEL selector = selectorFromString([NSString stringWithFormat:@"Button%d", i]);
    UIButton *button = [self performSelector:selector];
    button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}

Upvotes: 2

TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

Well, I guess you can put all of your buttons in an array, then fast enumerate through it.


NSArray *buttons; 
//Put all of your buttons inhere
for (UIButton *button in buttons)
{
    button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}

Upvotes: 1

Tharabas
Tharabas

Reputation: 3422

You may use an NSArray to iterate over:

UIFont *font = [UIFont fontWithName:@"myCustomFont" size:16];
NSArray *buttons = [NSArray arrayWithObjects: Button1, Button2, Button3, 
                                              Button4, Button5, Button6, 
                                              nil];
for (UIButton *button in buttons) {
  button.titleLabel.font = font;
}

Upvotes: 5

Related Questions