3

我有两件事看起来应该很容易,我打赌它们很容易,但这是我的第一个 Objective-C 程序,所以它不像我的本地 Perl 那样容易。这两个示例几乎相同,但我在想,因为使用@synthesize它的人可能会非常不同。

示例 1

// What Works
@synthesize display0 = _display0;
@synthesize display1 = _display1;
@synthesize display2 = _display2;
@synthesize display3 = _display3;

// What I would like to do:
for (int i=0; i<4; i++)
{
    @synthesize display$i = _display$i;
}

示例 2

// Works
- (IBAction)clearPressed
{
    self.display0.text = @"0";
    self.display1.text = @"0";
    self.display2.text = @"0";
    self.display3.text = @"0";
}

// What I would like to see
- (IBAction)clearPressed
{
    for (int i=0; i<4; i++) {
        self.display$i.text = @"0";
    }
}

任何让我朝着正确方向前进的帮助都会很棒!

4

6 回答 6

13

如果您使用 UILabel,不妨试试这个:

@property (nonatomic, retain) IBOutletCollection(UILabel) NSArray *valueFields;


- (IBAction)clearPressed
{
    for(UILabel *label in valueFields)
    {
        label.text = @"0";
    }
}
于 2012-12-27T14:19:48.660 回答
9

只需使用 IBOutletCollection:

@property (strong) IBOutletCollection(UILabel) NSArray *labels;

然后你可以使用快速枚举循环遍历它:

UILabel *label;
for (label in labels) {
    label.text = @"0";
}
于 2012-12-27T14:14:47.267 回答
4

One way would be using -valueForKey, which retrieves the value of the property-name passed to it. Combined with +stringWithFormat we can do something like this:

for (int i = 0; i < 4; i++) {
    NSString *key = [NSString stringWithFormat:@"display%i",i];
    UILabel *label = [self valueForKey:key];
    label.text = @"";
}

But you should consider using an array. If you are creating the labels in interface builder, use an IBOutletCollection.

//Connect to every label (.h)    
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *displays;

//Use a fast enumeration to clear every label
for (UILabel *label in self.displays) {
    label.text = @"";
}
//Setting one labels text from an array
[(UILabel *) self.displays[numberOfLabel] setText:@"text"];
于 2012-12-27T15:16:48.967 回答
0

使用键值观察

for (int i=0; i<4; i++) {
     [self setValue:@"0" forKeyPath:[[NSString alloc] initWithFormat:@"display%i", i]];
}
于 2012-12-28T10:02:31.603 回答
0

为什么不使用数组?

@property (nonatomic, strong) NSMutableArray *display;

@synthesize display;

- (IBAction)clearPressed
{
    for (int i=0; i<4; i++) {
        [self.display setObject:@"0" atIndexedSubscript:i];
    }
}
于 2012-12-27T14:12:50.240 回答
0

至于示例 1——如果您的 Xcode 最新版本不需要@synthesize,它会自动为您完成

示例 2——我不相信你想要做的事情可能像在 Objective-C 中那样(H2CO3 在他的回答中证明我错了),但如果你宁愿有一个循环,我会创建一个你的 UILabel 的 NSMutableArray 或UITextFields 和简单的循环使用它们:

for(UILabel *lbl in lblArray)
{
    lbl.text = @"0";
}

或者你可以遍历你的 UIViews 子视图并这样做:

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UILabel class]])
    {
        UILabel *lbl = (UILabel *)view;
        lbl.text = @"0";
    }
}
于 2012-12-27T14:15:22.207 回答