i have four textfields. User is allowed to enter only one digit in each text field.Once the user Enters single digit its focus should be on the next textfield. i have done this part and its working fine. Now, What i want is when i remove the text from the text field then its focus should move to previous textfield. i mean if i am deleting the text(digit) from the fourth text field then its focus should move to third text field. In short on removal of text the focus should be on previous textfield.
Now, what my problem is when i remove the text from the textfield then its focus moves to previous textfield but it clears the text of that textfield(the textfield on which i have set the focus).What i want is the text should not be removed on focus.
in .h file
IBOutlet UITextField *txtPinDigit1;
IBOutlet UITextField *txtPinDigit2;
IBOutlet UITextField *txtPinDigit3;
IBOutlet UITextField *txtPinDigit4;
UITextField *currentTextField;
in .m file
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textField.tag==0)
{
currentTextField=txtPinDigit1;
}
else if(textField.tag==1)
{
currentTextField=txtPinDigit2;
}
else if(textField.tag==2)
{
currentTextField=txtPinDigit3;
if(isDelete)
{
textField.text=digit3;
}
}
else if(textField.tag==3)
{
currentTextField=txtPinDigit4;
}
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(([textField.text length]==1)&&(![string isEqualToString:#""]))
{
if(currentTextField==txtPinDigit1)
{
[txtPinDigit2 becomeFirstResponder];
}
else if(currentTextField==txtPinDigit2)
{
[txtPinDigit3 becomeFirstResponder];
}
else if(currentTextField==txtPinDigit3)
{
[txtPinDigit4 becomeFirstResponder];
}
else if(currentTextField==txtPinDigit4)
{
textField.text = [textField.text substringToIndex:MAXLENGTH-1];
//[txtPinDigit4 resignFirstResponder];
//[txtPinDigit1 becomeFirstResponder];
}
}
else if([string isEqualToString:#""])
{
isDelete=YES;
NSLog(#"replacementString:%#",string);
// textField.text=string;
if(currentTextField==txtPinDigit4)
{
textField.text=string;
digit3=nil;
[digit3 release];
digit3=[[NSString alloc] initWithFormat:#"%i",[txtPinDigit3.text intValue]];
[txtPinDigit3 becomeFirstResponder];
}
else if(currentTextField==txtPinDigit3)
{
textField.text=string;
[txtPinDigit2 becomeFirstResponder];
}
else if(currentTextField==txtPinDigit2)
{
textField.text=string;
[txtPinDigit1 becomeFirstResponder];
}
else if(currentTextField==txtPinDigit1)
{
textField.text=string;
// [txtPinDigit1 resignFirstResponder];
//[txtPinDigit1 becomeFirstResponder];
}
}
return YES;
}
in the above code MAXLENGTH=1 defined.
any help will be appreciated.
thanks in advance.
Try This code, Change shouldChangeCharactersInRange: Delegate Method
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([newString length] < 1)
{
if (textField.tag==2)
{
[txtPinDigit1 performSelector:#selector(becomeFirstResponder) withObject:nil afterDelay:0.0];
// txt2.text=#"";
}
else if (textField.tag==3)
{
[txtPinDigit2 performSelector:#selector(becomeFirstResponder) withObject:nil afterDelay:0.0];
}
else if (textField.tag==4)
{
[txtPinDigit3 performSelector:#selector(becomeFirstResponder) withObject:nil afterDelay:0.0];
}
return YES;
} else
{
// Otherwise we cut the length of newString to 1 (if needed) and set it to the textField.
textField.text = [newString length] > 1 ? [newString substringToIndex:1] : newString;
if (textField.tag==1)
{
[textField resignFirstResponder];
[txtPinDigit2 becomeFirstResponder];
}
else if (textField.tag==2)
{
[textField resignFirstResponder];
[txtPinDigit3 becomeFirstResponder];
}
else if (textField.tag==3)
{
[textField resignFirstResponder];
[txtPinDigit4 becomeFirstResponder];
}
return NO;
}
}
Check to check length via this way and put a break point at beginning of shouldChangeCharactersInRange
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
int length = textField.text.length - range.length + string.length;
return YES;
}
I hope it will help you.
Before calling up to become first responder on filling up the 1st digit,bind the entered text inputs & the responder into dictionary...
On each previous/next condition,retrieve the information from the dictionary...The below example code is for the general previous/next custom actions(not auto though)..You just need to change the logic a bit based on the condition you prefer...
- (NSArray *) responders
{
if (_responders)
return _responders;
NSArray *textInputs = EditableTextInputsInView([[UIApplication sharedApplication] keyWindow]);
return [textInputs sortedArrayUsingComparator:^NSComparisonResult(UIView *textInput1, UIView *textInput2) {
UIView *commonAncestorView = textInput1.superview;
while (commonAncestorView && ![textInput2 isDescendantOfView:commonAncestorView])
commonAncestorView = commonAncestorView.superview;
CGRect frame1 = [textInput1 convertRect:textInput1.bounds toView:commonAncestorView];
CGRect frame2 = [textInput2 convertRect:textInput2.bounds toView:commonAncestorView];
return [#(CGRectGetMinY(frame1)) compare:#(CGRectGetMinY(frame2))];
}];
}
The below function should get called before doing previous/next auto tab.
- (Void) selectAdjacentResponder: (UISegmentedControl *) sender
{
NSArray *firstResponders = [self.responders filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UIResponder *responder, NSDictionary *bindings) {
return [responder isFirstResponder];
}]];
NSLog(#"%#",firstResponders);
UIResponder *firstResponder = [firstResponders lastObject];
NSInteger offset = sender.selectedSegmentIndex == 0 ? -1 : +1;
NSInteger firstResponderIndex = [self.responders indexOfObject:firstResponder];
NSInteger adjacentResponderIndex = firstResponderIndex != NSNotFound ? firstResponderIndex + offset : NSNotFound;
UIResponder *adjacentResponder = nil;
if (adjacentResponderIndex >= 0 && adjacentResponderIndex < (NSInteger)[self.responders count])
adjacentResponder = [self.responders objectAtIndex:adjacentResponderIndex];
[adjacentResponder becomeFirstResponder];
}
Bit lengthier,but this is all i know a BIT :)..Happy coding...
Related
I have more than one text field in my view controller how can i navigate from one to another using the return button in the IOS keyboard.
Use UITextFieldDelegate delegate and the textFieldShouldReturn: method. Inside you can get the tag of the textfield passed in argument and direct to another one based on this information.
To have the delegate working you have to set delegate property of sender (textfield) to be the receiver (e.g. your view controller)
myTextField.delegate = self;
or do it in the storyboard (here is some storyboard hints). Your view controller then needs to specify this delegate as follows (in the "h" file):
#interface MyViewController:UIViewController<UITextFieldDelegate>
#end
and then in the "m" file
-(BOOL)textFieldShouldReturn:(UITextField*)textfield{
if([textfield tag] == 1)
{
//pass focus to next textfield
[self.nextTextField becomeFirstResponder];
} else {
//remove focus from current textfield
[textfield resignFirstResponder];//
}
return YES;//YES if textfield should implement its default behaviour
}
-(BOOL) textFieldShouldReturn: (UITextField *) textField
{
[textField resignFirstResponder];
if(textField == _your1stTextField)
[_your2ndTextField becomeFirstResponder];
return YES;
}
try this...
set delegates to all of your text fields and then..
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == textField1)
{
[textField2 becomeFirstResponder];
}
else if (textField == textField2)
{
[textField3 becomeFirstResponder];
}
else if textField == textField3)
{
[textField4 becomeFirstResponder];
}
.
.
.
[textField resignFirstResponder];
return YES;
}
I think this solution is more dynamic as it works for any number of textFields as long as your superview doesn't have a view with a tag == lastTextField.tag + 1
In viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
self.textField1.delegate = self;
self.textField2.delegate = self;
...
self.lastTextField.delegate = self;
self.textField1.tag = 1;
self.textField2.tag = 2;
...
self.lastTextField.tag = n;
}
Then implement the textFieldDelegate:
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder)
[nextResponder becomeFirstResponder];
else
[textField resignFirstResponder];
return NO;
}
You need to declare at .h
.m set
yourTextfieldRef1.delegate=self;
yourTextfieldRef2.delegate=self;
yourTextfieldRef3.delegate=self;
yourTextfieldRef4.delegate=self;
yourTextfieldRef5.delegate=self;
.
.
.
set
yourTextFieldRef1.tag=1;
yourTextFieldRef2.tag=2;
yourTextFieldRef3.tag=3;
yourTextFieldRef4.tag=4;
yourTextFieldRef5.tag=5;
.
.
.
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return YES;
}
Hope it helps you...!
I want to add some strings after end editing in UITextField.
Example :
textfield 1 : user input 1000 . After focus to textfield2,I want to add "miles" to textfield1. => textfield1 : 1000 miles
And if user focus to textfield1 again, it shows only 1000 for user edit, do not have "miles".
I tried but it not work
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
UITouch *touch = [[event allTouches] anyObject];
if ([textfield1 isFirstResponder] && (textfield1 != touch.view))
{
textfield1.text = [NSString stringWithFormat:#"miles"];
}
if ([textfield2 isFirstResponder] && (textfield2 != touch.view))
{
....
}
}
you can use the delegate methods of UITextField to do this
- (void)textFieldDidBeginEditing:(UITextField *)textField;
and
- (void)textFieldDidEndEditing:(UITextField *)textField;
Bernhard
please try this,
- (void)textFieldShouldBeginEditing:(UITextField *)textField
{
textField.text=#"";
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
textfield1.text = [NSString stringWithFormat:#"%# miles",textField.text];
}
here textFieldDidEndEditing is textField's delegate method. you need to set textfield1.delegate=self.
hope this code will help you.
Try this :-
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(textField.tag==10) // textfield 1
{
if(![ _txt1.text rangeOfString:#"miles"].location!= NSNotFound)
{
_txt1.text = [_txt1.text stringByAppendingString:#"miles"];
}
}
else if (textField.tag == 20) // textfield 2
{
if([ _txt1.text rangeOfString:#"miles"].location!= NSNotFound)
{
_txt1.text = [_txtUser1.text stringByReplacingOccurrencesOfString:#"miles" withString:#""];
}
}
}
NOTE:- Set tag to your textfields as 10 & 20._txt1 is your textfield1 (UITextfield)
Make text global variable of NSString and then
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(text.length>0)
{
self.textField.text =text;
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
text =self.txtField.text;
self.txtField.text = [NSString stringWithFormat:#"%# miles", text];
}
Set the delagate of your textfield, like below
#interface YourController : UIViewController <UITextFeildDelegate>
and then use the following methods to check
-(void)textFieldDidEndEditing:(UITextField *)textField{
if(textField....) //condition to check textfeild is
{
//do your stuff
}
}
Hope this helps
set tag for textField1 like this
self.textField1.tag = 100;
on viewDidLoad to your textField outlet, then
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if (textField.tag == 100)
{
self.txtUserId.text = [NSString stringWithFormat:#"%# miles", self.txtUserId.text];
}
}
since this is a delegate method it will fire for each textField end edit event that is why you have to check with tag number. and dont forget to set the delegate
#interface YourController : UIViewController <UITextFeildDelegate>
The next code will work only when the user will enter the third character. I want the focus to move TextField when the user enters the second character but still keep the first 2 characters in the first TextField. if I'll try something likenewString.length < 2 , when entering 2 characters in a row I'll get the first character in the first UITextField and the second character in the second UITextField.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (newString.length <= 2 )
{
return YES;
}
else
{
NSInteger nextTag;
nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
[nextResponder becomeFirstResponder];
}
else {
[textField resignFirstResponder];
}
}
return YES;
}
I belive this should work:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(newString.length == 2)
{
UIResponder* nextResponder = [textField.superview viewWithTag:textField.tag + 1];
if (nextResponder) {
[nextResponder performSelector:#selector(becomeFirstResponder) withObject:nil afterDelay:0.1];
}
else {
[textField resignFirstResponder];
}
}
return newString.length <= 2;
}
Please try it and tell me if it works. If not please tell me a bit more about your setup and I will try to set up a view like yours and it will be easier for me to try solutions.
Ok, EDIT The above works. It is not very beautiful but it does the job. It is sad that apple would not add a method for didChangeCharactersInRange which would be much more appropriate for this.
EDIT Edited according to Sha's findings 0.1 instead of 0 in the timer interval
EDIT Changed according to Mike's suggestion
i have 6 textfields named digit1,digit2..etc upto digit6 added as a subview over a view. i want the digit2 textfield to autofocus once the user enters a digit in the digit1 textfield and similarly digit3 should autofocus when a digit is entered in digit2 textfield.Below shown is the code i tried.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.text.length>=1)
{
[textField resignFirstResponder];
UITextField *_textField=(UITextField*) [self.view viewWithTag:textField.tag+1];
[_textField becomeFirstResponder];
}
return TRUE;
}
What happens here is when i enter a digit in digit1 it dosent appear in digit 1 but it appears in digit2 and also when i click delete button the control is transfered to the subsequent textfields rather than deleting the text in the current textfield.Please help me to fix this.
lets assume that you have 3 textfields with names such as t1, t2 and t3
set tag value for t1 = 1, t2 = 3 and t3 = 3
set tag values for all the textfields and the write this code
then write this code
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
switch(textField.tag){
case 1:{
if(textField.text.length>=1)
{
[t1 resignFirstResponder];
[t2 becomeFirstResponder];
break;
}
}
case 2:{
if(textField.text.length>=1)
{
[t2 resignFirstResponder];
[t3 becomeFirstResponder];
break;
}
}
case 3:{
if(textField.text.length>=1)
{
[t3 resignFirstResponder];
break;
}
}
}
}
return TRUE;
}
I think the problem is that shouldChangeCharactersInRange gets called before the edit actually occurs. Since you are changing the first responder in there, the edit takes effect in the new first responder instead of the old one.
You could try moving the code inside your if block to another method, and calling it with [self performselector:withObject:afterDelay], setting the delay to some small value. Something like:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.text.length>=1)
{
[self performSelector:#selector(switchTextField) withObject:nil afterDelay:0.1];
}
return TRUE;
}
-(void)switchTextField
{
[textField resignFirstResponder];
UITextField *_textField=(UITextField*) [self.view viewWithTag:textField.tag+1];
[_textField becomeFirstResponder];
}
That way shouldChangeCharactersInRange returns true immediately (as it should), the edit will take place in the currently selected textField, and then your switchTextField method will get called soon after. It's not the cleanest solution, but it's the quickest I can think of off the top of my head.
I found the solution
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string];
if( [str length] > 0 ){
textField.text = string;
UIResponder* nextResponder = [textField.superview viewWithTag:(textField.tag + 1)];
if (nextResponder) {
[nextResponder becomeFirstResponder];
}
return NO;
}
return YES;
}
My app has a registration view, I compare strings in password textfield and confirm password textfield , if they dont match I want user go back to password textfield
This question done it with using tags
UITextField jump to previous
Is there a way to accomplish this without using tags?
//call next textfield on each next button
- (BOOL) textFieldShouldReturn:(UITextField *) textField {
BOOL didResign = [textField resignFirstResponder];
if (!didResign) return NO;
if ([textField isKindOfClass:[SOTextField class]])
dispatch_async(dispatch_get_current_queue(),
^ { [[(SOTextField *)textField nextField] becomeFirstResponder]; });
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
if (textField==self.confirmPassword) {
if ([self.password.text isEqualToString:self.confirmPassword.text]) {
NSLog(#"password fields are equal");
}
else{
NSLog(#"password fields are not equal prompt user to enter correct values");
//[self.password becomeFirstResponder]; doesnt work
}
}
}
Without using tags, you could create an NSArray of textfield outlets the describes the desired ordering.
Declare and init like this ...
#property(nonatomic,strong) NSArray *textFields;
- (NSArray *)textFields {
if (!_textFields) {
// just made these outlets up, put your real outlets in here...
_textFields = [NSArray arrayWithObjects:self.username, self.password, nil];
}
return _textFields;
}
You'll need to fetch the text field that currently has focus, if there is one...
- (UITextField *)firstResponderTextField {
for (UITextField *textField in self.textFields) {
if ([textField isFirstResponder]) return textField;
}
return nil;
}
Then advance focus like this...
- (void)nextFocus {
UITextField *focusField = [self firstResponderTextField];
// what should we do if none of the fields have focus? nothing
if (!focusField) return;
NSInteger index = [self.textFields indexOfObject:textField];
// advance the index in a ring
index = (index == self.textFields.count-1)? 0 : index+1;
UITextField *newFocusField = [self.textFields objectAtIndex:index];
[newFocusField becomeFirstResponder];
}
And move focus backward like this...
- (void)previousFocus {
UITextField *focusField = [self firstResponderTextField];
// what should we do if none of the fields have focus? nothing
if (!focusField) return;
NSInteger index = [self.textFields indexOfObject:textField];
// backup the index in a ring
index = (index == 0)? self.textFields.count-1 : index-1;
UITextField *newFocusField = [self.textFields objectAtIndex:index];
[newFocusField becomeFirstResponder];
}