How to construct IBOutlet names in code in order to change them?
Let's say I've got several UI开发者_开发问答Labels which have been set up in IB and connected to IBOulets in code (label1, label2, label3, label4)
How would I create these variable names within code, so that I could change the text of each one in a loop, where the labels are taken from a NSArray.
Here's the pseudo-code:
labelArray = [NSArray arrayWithObjects:@"this", @"array", @"has", @"a", @"random", @"amount", @"of", @"items", nil];
for (int i = 0; i < [labelArray count]; i++)
{
// labelx is the constructed name of the IBOutlet
lablex.text = [labelArray objectAtIndex:i];
}
How do I construct 'labelx' above? Could this be done using Blocks?
You would have to initialize the array at some place, using
labelArray = [NSArray arrayWithObjects:@"this", @"array", @"has", nil];
uiLabelArray = [NSArray arrayWithObjects:label1,label2,label3,nil];
then
for (int i = 0; i < [uiLabelArray count]; i++)
{
[uiLabelArray objectAtIndex:i].text = [labelArray objectAtIndex:i];
}
You can use key value coding (KVC). It would look something like:
[[self valueForKey:[NSString stringWithFormat:@"label%d", i]] setText:[labelArray objectAtIndex:i]];
More info can be found here
精彩评论