Question

I was just wondering if there is a way to simplify or have multiple items in the one "self" statement. I currently have about 5 UITextfields and the code is just repeating its self but only targeting different textfields.

The code is below:

self.cell1Field1Dismiss.inputAccessoryView = numberToolbar;
self.cell1Field2Dismiss.inputAccessoryView = numberToolbar;
self.cell2Field1Dismiss.inputAccessoryView = numberToolbar;
self.cell2Field2Dismiss.inputAccessoryView = numberToolbar;
self.cell3Field1Dismiss.inputAccessoryView = numberToolbar;
self.cell3Field2Dismiss.inputAccessoryView = numberToolbar;
self.cell4Field1Dismiss.inputAccessoryView = numberToolbar;
self.cell4Field2Dismiss.inputAccessoryView = numberToolbar;
self.cell5Field1Dismiss.inputAccessoryView = numberToolbar;
self.cell5Field2Dismiss.inputAccessoryView = numberToolbar;

Is there a way to have something like: (this doesn't work for some reason)

self.cell1Field1Dismiss, cell1Field2Dismiss, etc... .inputAccessoryView = numberToolbar
Was it helpful?

Solution

Use an IBOutletCollection to hold a reference to all of your textfields instead of individual IBOutlets. This works the same way as connecting IBOutlets.

Declare a property like so

@property (nonatomic, strong) IBOutletCollection(UITextField) NSArray *textFields;

Then iterate through all the textfields and set whatever properties you want.

for (UITextField *textField in self.textFields) {
    textField.inputAccessoryView = numberToolbar;
}

OTHER TIPS

According to @Kevin , here is my upgrade:

[self.textFields enumerateObjectsUsingBlock:^(UITextField *textField, NSUInteger idx, BOOL *stop) {
    textField.inputAccessoryView = numberToolbar;
}];

Block methods of collection class are recommended personally (Thanks to @Patrick Goley). There are a lot of issues talking about that: When to use enumerateObjectsUsingBlock vs. for http://www.mikeabdullah.net/slow-block-based-dictionary-enumeration.html Finally(I think it is right): http://lists.apple.com/archives/objc-language/2012/Sep/msg00012.html

If you want all of the text fields in your view to have the same inputAccessoryView you can do the following:

for (UIView *view in[self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)view;
        textField.inputAccessoryView = numberToolbar;
    }
}

Try the below code. Similar to assigning the values for integer/float/.. variables you can assign like below.

self.cell1Field1Dismiss.inputAccessoryView = self.cell1Field2Dismiss.inputAccessoryView = self.cell2Field1Dismiss.inputAccessoryView = .......... = numberToolbar

Hope this will help you.. If it not works let me know..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top