IOS从字符串变量调用UIButton

时间:2014-11-20 19:23:04

标签: ios for-loop uibutton

我正在寻找一种更好的方法来将图像设置为我的所有按钮。现在我正在使用for循环,但必须单独调用每个按钮。它太丑了,太长了。

@property (weak, nonatomic) IBOutlet UIButton *box0;
@property (weak, nonatomic) IBOutlet UIButton *box1;
// up to 150 of them on the page
@property (weak, nonatomic) IBOutlet UIButton *box150;

@end

@implementation HelpTwo
{
    bool checked0;
    bool checked1;
    bool checked2;
    bool checked3;
}

以及有问题的部分

NSArray *boxes = [draftboxeschecked componentsSeparatedByString:@","];
    // pulled from DB and as an example could be 0,1,8,19,29

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];
        checked0 = YES;
    } else if ([box isEqualToString:@"1"]) {
        [_box1 setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
        checked1 = YES;
    }
    else if ([box isEqualToString:@"2"]) {
        [_box2 setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
        checked2 = YES;
    }
    else if ([box isEqualToString:@"3"]) {
        [_box3 setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
        checked3 = YES;
    }

// all the way to 150

我正在尝试做什么,但它无法正常工作

NSArray *boxes = [draftboxeschecked componentsSeparatedByString:@","];

for (NSString *boxNumber in boxes) {

    NSString *modifiedBox = [NSString stringWithFormat:@"_box%@",boxNumber];
    bool check = [NSString stringWithFormat:@"checked%@",boxNumber]; 

    [modifiedBox setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
    check = YES;  
}

修改

这似乎适用于图像。仍然需要添加布尔值。我将所有按钮添加到IBOutletCollection并为每个按钮设置标记号。该集合名为buttonCollection。

NSArray *boxes = [draftboxeschecked componentsSeparatedByString:@","];

for (NSString *boxNumber in boxes) {

    for (UIButton *button in _buttonCollection) {
        if (button.tag == boxNumber.intValue) {
            // set image
            [button setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
        }
    }


}

1 个答案:

答案 0 :(得分:-1)

不确定您使用的是check_#for。这是一个解决方案(但我不一定推荐它)。我不确定你用check bool做了什么,所以我把它遗漏了。

NSArray *boxes = [draftboxeschecked componentsSeparatedByString:@","];
for (NSString *boxNumber in boxes) {
  NSString *boxSelectorString = [NSString stringWithFormat:@"box%@", boxNumber];
  // Assuming the properties are on the self object, they should create selectors that
  // match the property name.
  // Note: I'm not familiar with IBOutlets.
  UIButton *boxButton = [self performSelector:NSSelectorFromString(boxSelectorString)];
  [boxButton setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
}