Reputation: 5936
If I have 100 UITextFields,
myTextfFeld1
, myTextField2
...and so on until mytextField100
...and they all perform the same action, say change myTextField1.alpha = 0.4
to myTextField1.alpha = 1
.
Rather than write this out 100 times is there a more efficient way of doing this
I had a look here iOS looping over an object's properties and adding actions but it still means adding all the UITextFields
into the array.
Upvotes: 1
Views: 150
Reputation: 217
Use a loop and an array for the textfields. e.g.
int i = 0
do textfield[i].alpha = 1
i = i+1
until i = 100
Upvotes: -2
Reputation: 119031
You can define an outlet collection and connect all of the textfields to it from the XIB:
@property (nonatomic, weak) IBOutletCollection(UITextField) NSArray *textFields;
Then you can loop over the textFields
array.
Upvotes: 1
Reputation:
Please, no!
Use an array, seriously. Don't you dare having 100 instance variables named textField1
to textField100
!
Just in order to actually answer your question: you still can do this. Again, I strongly discourage doing it, but just for completeness' sake, here's the code:
for (int i = 1; i <= 100; i++) {
NSString *ivarName = [NSString stringWithFormat:@"myTextField%d", i];
UITextField *tf = [self valueForKey:ivarName];
[tf doWhateverYouWant];
}
Reflection in Objective-C is awesome, isn't it? Not quite when abused.
Upvotes: 6