从我创建的字符串(使用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中通过从数组中选择正确的键从字符串中选择要使用的Label。而不是做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];
谢谢。
答案 0 :(得分: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"];