在变量的末尾添加int

时间:2016-03-22 10:08:45

标签: objective-c apple-watch watch-os

我在视图中有16个按钮,命名为:

@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb1;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb2;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb3;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb4;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb5;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb6;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb7;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb8;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb9;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb10;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb11;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb12;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb13;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb14;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb15;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *bb16;

我想根据switch语句中的不同条件设置图像的背景。所以我正在做的是我有一个for循环

 for (int i=1; i<=16; i++) {
int val = [(NSNumber *)[self.valuesArray objectAtIndex:i] intValue];
    NSString *newString = [NSString stringWithFormat:@"bb%d",i];
    switch (val) {
                case 4:
                    [**self.bb%d** setBackgroundImageNamed:@"s"];
                    break;

                default:
                    break;
            }
    }

val是当前从NSArray中选取的值,而下面是创建所需字符串的newString**内的文字是我坚持的东西当然我把**我的自我强调了问题。我想根据不同的情况更改按钮的背景图像。因此,如果是4,则将其更改为s,如果0将其更改为其他内容。那么我该怎样才能实现它。我希望我的问题很明确。

1 个答案:

答案 0 :(得分:0)

如果您不希望在应用程序结构中进行太多更改,则可以执行此操作。

  1. 尝试在initWithCoder方法中将所有16个WKInterfaceButton对象放在NSMutableArray中。(如果需要,将此数组设为全局)。

    #import "YourClass.h"
    
    @interface YourClass()
    
    @property (nonatomic,strong) NSMutableArray * btnArray;
    
    @end
    
    @implementation YourClass
    
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
         if (self = [super initWithCoder:aDecoder]) {
    
           _btnArray = [NSMutableArray array];
           [_btnArray addObject:bb1];
           /*
           .
           .
           .
           Add all 16 buttons like this here */
       }
       return self;
    } 
    
  2. 在switch语句的特定情况下,按索引获取对象,然后设置它的背景图像。

    for (int i=1; i<=16; i++) {
    int val = [(NSNumber *)[self.valuesArray objectAtIndex:i] intValue];
    NSString *newString = [NSString stringWithFormat:@"bb%d",i];
     switch (val) {
            case 4:
                [((WKInterfaceButton *)[_btnArray objectAtIndex:i-1]) setBackgroundImageNamed:@"s"];
                  break;
    
              default:
                  break;
           }
       }