Esqarrouth Esqarrouth - 3 months ago 14
iOS Question

Text Field Should Return, is this correct for ios7?

I have searched and seen a lot of answers about textFieldShouldReturn method. Half of them are outdated, some work in different cases, some are not explained thoroughly. I am not sure what is the most optimal way to do this task, it works but I think there might be an easier way to do it.

Heres my code so far:

On the header file:

@interface ClassName : SomeUIViewController <UITextFieldDelegate>


In the implementation file:

@interface ClassName()

@property (weak, nonatomic) IBOutlet UITextField *firstOne;
@property (weak, nonatomic) IBOutlet UITextField *secondOne;
@property (weak, nonatomic) IBOutlet UITextField *thirdOne;
@property (weak, nonatomic) IBOutlet UITextField *fourthOne;
@property (weak, nonatomic) IBOutlet UITextField *fifthOne;

@end

-(void)viewDidLoad{
self.firstOne.delegate = self;
self.secondOne.delegate = self;
self.thirdOne.delegate = self;
self.fourthOne.delegate = self;
self.fifthOne.delegate = self;
}

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
if (textField == self.firstOne) {
[textField resignFirstResponder];
[self.secondOne becomeFirstResponder];
} else if (textField == self.secondOne) {
[textField resignFirstResponder];
[self.thirdOne becomeFirstResponder];
} else if (textField == self.thirdOne) {
[textField resignFirstResponder];
[self.fourthOne becomeFirstResponder];
} else if (textField == self.fourthOne) {
[textField resignFirstResponder];
[self.fifthOne becomeFirstResponder];
} else if (textField == self.fifthOne) {
[textField resignFirstResponder];
}

return NO;
}


So is this correct or are there better ways to do this task?

Answer

In general your code is fine.

If you are using IB (Interface Builder) you can set the delegate there instead of in code.

Example: control drag from the UITextField to the ViewController and select "delegate". enter image description here

The resignFirstResponder could be factored to ibe occurrence
Refactored code:

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
    [textField resignFirstResponder];

    if (textField == self.firstOne) {
        [self.secondOne becomeFirstResponder];
    } else if (textField == self.secondOne) {
        [self.thirdOne becomeFirstResponder];
    } else if (textField == self.thirdOne) {
        [self.fourthOne becomeFirstResponder];
    } else if (textField == self.fourthOne) {
        [self.fifthOne becomeFirstResponder];
    }

    return NO; 
}