2013-02-19 45 views
0

從字符串我創建(使用的Xcode 4.5.2)的XCode更名出口標籤方向

- (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爲裏面,只需從數組中選擇正確的密鑰即可從字符串中選擇要使用的標籤。而不是如果或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),並從我創建的一組數組中調用它,並告訴哪個標籤要使用。

我都試過,但當然這不工作,沒有什麼接近正確答案,但希望這能更好地解釋我想要什麼(很抱歉提前壞的編碼):

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

謝謝您。

回答

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"]; 
+0

謝謝你,我沒有告訴正是我在做什麼,我只是想對不起使我的代碼的某些部分更少重複。 – joseamck 2013-02-20 00:57:50