Variable IBOutlet name?

2019-09-15 03:23发布

问题:

Is it possible to have a variable outlet name?. For example you have 10 labels (perhaps seats on bus). each has an outlet, seat1 seat2 etc. Is it possible to have a for loop that concatenates @"seat" to the increment integer. So that I can access seat1, seat2 outlet without having to specify it individually. This doesn’t work but makes it a bit clearer what I am trying to achieve.

int i;
for (i = 0; i < [seatarray count]; i++)
{
    [@”seat”  stringByAppendingString[ i stringValue]] = @””;
}

回答1:

Starting iOS4 you can use IBOutletCollection which allows to connect multiple instances to a single outlet which represents an array of objects, e.g. IBOutletCollection which can store UILabels only:

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


回答2:

It might be easier to simply create the array yourself at load time:

self.seatarray = [NSArray arrayWithObjects:seat1, seat2, ..., seatN, nil];


回答3:

You should be able to do that with key-value coding, something like (untested code)
for (int i = 0; i != 10; ++i) { [self setValue:@"foo" forKey:[@"seat" stringByAppendingFormat:@"%d", i]]; }