Reputation: 572
I have a relatively large iPhone application with many views. I would like implement a next/previous option on my keyboard. I have managed to implement it UI-wise, with some code examples i saw online, but all of them are assuming we need to add code to each view controller to implement the actual transition between the text fields.
My question is: is there a general way to know, given some text field, who is the next field in order? (i.e without refactoring each of my view controllers)
I ask this question because when i use the iPhone simulator and press the computer's Tab key - the switch between the fields happen, so i wonder if there is a built-in or generic way to implement it on iOS.
clarification: is there a way of doing it without adding a specific code for each type of view controller? (adding a generic code is acceptable)
Upvotes: 1
Views: 2490
Reputation: 572
I want to write how i solved this problem, with the help of many good answers given to me here :)
First, i could not create fully generic code that creates tab regardless of the view it is in. Instead i created this thing, which i think is the most generic solution with the firstResponder method not working:
I hope you could benefit from this, and again thanks for all the good answers
Upvotes: 2
Reputation: 3152
This is some generic code that I came up with:
// add a property for the fieldsArray
//add this in viewDidLoad
_fieldsArray = [[NSMutableArray alloc] init];
NSArray *viewsArray = [self.view subviews];
for (id view in viewsArray) {
if ([view isKindOfClass:NSClassFromString(@"UITextField")]) {
[_fieldsArray addObject:view];
}
}
//add this in your action that switches the fields
for (UITextField *field in _fieldsArray) {
if ([field isFirstResponder]) {
if ([fieldsArray lastObject] == field) {
[_fieldsArray[0] becomeFirstResponder];
}else {
NSUInteger nextIndex = [_fieldsArray indexOfObject:field] + 1;
[_fieldsArray[nextIndex] becomeFirstResponder];
}
break;
}
}
Before using it it should be improved.
1) find all subviews of self.view
recursively
2) do some checks if the arrays are empty or nil or have just one object in them.
Good luck!
Upvotes: 0
Reputation: 1742
you could have a method in a utility class that takes as arguments a textfield and a viewcontroller. then you could use the "tag"-attribute of the textfields to find the next textfield in that viewcotroller, assuming that you assigned the tags accordingly. numbers would be great, i think. a simple callback method in the vc could handle the focus-change. thats about as generic as i can see right now.
Upvotes: 0