我需要在编号数组中的多个按钮上设置默认值。现在我正在使用if语句,但它太长了,并且必须有一个更好的方法可能有一个循环?
当前代码
@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];
}
}
答案 0 :(得分:1)
您可以将按钮添加到IBOutletCollection
并在按钮上设置tags
,然后执行以下操作:
...
for (UIButton *button in myButtonCollection) {
if (button.tag == box.intValue) {
// set image
}
}
或者只是将它们添加到数组中:
NSArray *buttons = @[_box1, _box2 ...