Reputation: 247
I need to set default values on multiple buttons from a numbered array. Right now I am using an if statement but it is way too long and there must be a better way perhaps with a loop?
Current Code
@interface HelpPage()
@property (weak, nonatomic) IBOutlet UIButton *box0;
@property (weak, nonatomic) IBOutlet UIButton *box1;
@property (weak, nonatomic) IBOutlet UIButton *box2;
@property (weak, nonatomic) IBOutlet UIButton *box3;
@property (weak, nonatomic) IBOutlet UIButton *box4;
@property (weak, nonatomic) IBOutlet UIButton *box5;
// I have over 120 buttons on this screen
@end
@implementation Help
NSMutableArray *boxes = [NSMutableArray arrayWithArray:[defaults objectForKey:@"helpboxeschecked"];
NSInteger i;
for (i=0; i < boxes.count; i++) {
NSString *box = boxes[i];
if ([box isEqualToString:@"0"]) {
[_box0 setImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateNormal];
}
if ([box isEqualToString:@"1"]) {
[_box1 setImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateNormal];
}
if ([box isEqualToString:@"2"]) {
[_box2 setImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateNormal];
}
// and so on for all boxes
}
// **Isn't there a way to have it be**
for (i=0; i < boxes.count; i++) {
if ([box[i] = i) {
[_box[i] setImage:[UIIMage imageNamed:@"checked.png"] forState: UIControlStateNormal];
}
}
Upvotes: 0
Views: 74
Reputation: 7343
You can either add your buttons to an IBOutletCollection
and set tags
on your buttons and do something like:
...
for (UIButton *button in myButtonCollection) {
if (button.tag == box.intValue) {
// set image
}
}
or just add them to an array:
NSArray *buttons = @[_box1, _box2 ...
Upvotes: 1