0

从我创建的字符串(使用 xcode 4.5.2)

   - (void)viewDidLoad{ 
      myList = [[NSArray alloc] initWithObjects:@"x",@"y",@"z", nil];
      }

当然还有:

@property (strong, nonatomic) IBOutlet UILabel *labelField_x;
@property (strong, nonatomic) IBOutlet UILabel *labelField_y;
@property (strong, nonatomic) IBOutlet UILabel *labelField_z;

我希望能够在 IBAction 中通过从数组中选择正确的键来从字符串中选择要使用的标签。而不是做 if 或 BOOL 语句并重复我自己。表单示例我有这个:

- (IBAction)buttonPressed:(UIButton *)sender;
{
    if (is_x){

        NSString *digit = sender.currentTitle;
            if (!pressedDecimal){
                labelField_x.text = [labelField_x.text stringByAppendingString:digit];
            }else if (count <= 1){
                labelField_x.text = [labelField_x.text stringByAppendingString:digit];
            }
                                      .
                                      .
                                      .
    }
    else if (is_y){

        NSString *digit = sender.currentTitle;     
            if (!pressedDecimal){
                labelField_y.text = [labelField_y.text stringByAppendingString:digit];
            }else if (count <= 1){
                labelField_y.text = [labelField_y.text stringByAppendingString:digit];
            }
                                      .
                                      .
                                      .

    }
    else if (is_z){

        NSString *digit = sender.currentTitle;
            if (!pressedDecimal){
                labelField_z.text = [labelField_z.text stringByAppendingString:digit];
            }else if (count <= 1){
                labelField_z.text = [labelField_z.text stringByAppendingString:digit];
            }
                                      .
                                      .
                                      .
    }
}

如您所见,我每次都使用相同的代码重复我自己,而不是仅更改位置或 UILabel 方向或它指向标签的任何内容( labelField_x, labelField_y, labelField_z )。我的问题是是否有办法只更改最后一个字符串 (x, y, z) 并从我创建的一组数组中调用它并告诉使用哪个标签。

我已经尝试过了,但当然它不起作用,并且与正确答案没有什么关系,但希望这可以更好地解释我想要的东西(提前抱歉编码不好):

labelField_@"%@".text,[myList 0]  = [labelField_@"%@".text,[myList 0] stringByAppendingString:digit];

谢谢你。

4

1 回答 1

0

我不完全确定您在做什么,但是如果您想节省一些打字时间,为什么不这样做:

// assign the label you want to use to a local variable

UILabel *selectedLabel;
selectedLabel = nil;
if (is_x) {
    selectedLabel = labelField_x;
} else if (is_y) {
    selectedLabel = labelField_y;
} else if (is_z) {
    selectedLabel = labelField_z;
}

// now work with selectedLabel so you don't have to repeat yourself

if (!pressedDecimal){
    selectedLabel.text = ...

或者您甚至可以将 IBOutlet 属性中的标签直接粘贴到字典中,以便您可以快速获取任何给定字符(字符串)的正确标签:

// create a lookup dictionary (once, e.g. in awakeFromNib)

NSDictionary *labelForCharacter;
labelForCharacter = @{
    @"x" : labelField_x,
    @"y" : labelField_y,
    @"z" : labelField_z
};

 // get the label for "z"

UILabel *selectedLabel;
selectedLabel = labelForCharacter[@"z"];
于 2013-02-19T23:37:25.657 回答