Detect the current input character in UITextField(iOS) - iphone

I want to know the current input character the user just inputted.Comparing the old and the new input string seems to work, but it must be the last thing I'd like to try.Any suggestion? I guess there are some methods in iOS SDK that can do this in a better way.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
from the UITextFieldDelegate should help you.
It is not only called for replacing text, also whenever the user presses a key on keyboard.
(length of range will be 0 then and the location will be the current insertation position).
See the documentation for more information:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html#//apple_ref/doc/uid/TP40006991-CH3-SW9

If you want to compare the strings as the characters come in, your better off using
[textField addTarget:self action:#selector(compareInput) forControlEvents:UIControlEventEditingChanged];
-(void)compareInput
{
if ([textField.text isEqualToString:compareString])
NSLog(#"They're the same!");
}
than the delegate:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
If you literally just want to compare characters, then the delegate method is fine. The variable string contains the typed character.
For example, this is what happens with the above methods when a user types foo into the UITextField:
User types: f, this happens:
[textField addTarget:self action:#selector(compareInput) forControlEvents:UIControlEventEditingChanged];
calls compareInput immediately, and the letter f is available via textField.text:
-(void)compareInput
{
NSLog(textField.text); //prints `f`
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(textField.text); //prints nothing
return YES;
//after returning YES, textField.text will contain `f`
}
User types: o, this happens:
[textField addTarget:self action:#selector(compareInput) forControlEvents:UIControlEventEditingChanged];
calls compareInput immediately, and the string fo is available via textField.text:
-(void)compareInput
{
NSLog(textField.text); //prints `fo`
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(textField.text); //prints `f`
return YES;
//after returning YES, textField.text will contain `fo`
}
I'm probably not very clear, but I hope it gives you some insight!

This method will show current input in UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *letters;
if ([textField.text isEqualToString:#""]){
letters = string;
}else if ([string isEqualToString:#""]){
if ([textField.text length] > 0) {
letters = [textField.text substringToIndex:[textField.text length] - 1];
}
}else{
letters = [textField.text stringByAppendingString:string];
}
NSLog(#"letters %#\n", letters);
return YES;
}

Related

Calling a method only after shouldChangeCharactersInRange returns yes

I have a UITextField with a table below it showing a list of items to select from (similar to drop down list). Now for example when i type 2 in textfield (textfield has Year values), the table would show all strings with 2 as substring. So when i type in 2000, it would only show matching string 2000 in the table.
Now when i finish typing 2000 in the textfield i want to call a method. Everything works fine but i want to call this method only when i finish typing all 4 digits but here the method is called when i try to enter 4th digit.
How can i perform this where i type in 2000 and it will call the method after shouldChangeCharactersInRange return Yes after entering 3rd zero.
Here's my code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
//if _filteredarray count==1 and substring and _filteredarray object at index 0 matches then call a method here
return YES;
}
Try this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
if(substring.length == 4)
{
[textField resignFirstresponder];
[self performSelector:#selector(functiontocall)withObject:nil afterDelay:0.8];
}
return YES;
}
the above code may give u an idea
if u enter fourth letter of 2000, then the keyboard will disappear(if u want u can add it, which will avoid further entering values to textfield), then u can see the third zero for 0.8 seconds and the function u need to call will be called.

Autocomplete email functionality in UITextField

I want to implement a same autocomplete email functionality as showing in above screen in my UITextField
Please suggest
Do as follows,
1)store the emails
2)When the user starts type the text in textField search the stored valu and display the values in UITableView
You should use the following delegate of UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
What kingOfBliss said is the correct way. anyhow i will provide you some logic of the code.
Try tis code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
for(NSString *particularEmail in arrayContainsAllEmailAddress)
{
NSString *firstLetter = #"";
NSInteger stringlen=[string length];
if(particularEmail.length >= stringlen)
{
firstLetter = [particularEmail substringToIndex:stringlen];
}
if(firstLetter.length > 0)
{
if([string.uppercaseString isEqualToString:firstLetter.uppercaseString])
{
[tableArray addObject:particularEmail];
//tableArray is the array which u will load into the tableview. This contains the emails that matches your search name.
}
}
}
// Add your tableArray into UITableView
}

delete last character UITextField

I have an UITextField and I would like that for every tap on a character, the first character is deleted. So that I just have one character in my textField every time. Moreover I would like it to display every tap in the console log.
How can I do this?
You need to implement shouldChangeCharactersInRange method in your text field delegate:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:
(NSRange)range replacementString:(NSString *)string{
textField.text = #"";
return YES;
}
You may need to check for range and string values to cover all possible cases (like copy/paste actions). This code just sets the text field's value to the last typed character.
UITextField inherits from UIControl, so you can use the target-action mechanism that is part of the UIControl class:
[textField addTarget:self action:#selector(updateTextField) forControlEvents:UIControlEventValueChanged];
In the action method, you can replace the UITextField's text with only the last character and log that character in the console. Note that since changing the UITextField's text will again result in the "updateTextField" message being sent a second time to the target, you will need some kind of mechanism for determining whether to update or not:
- (void)updateTextField {
if(updateTextField == YES) {
updateTextField = NO;
NSString *lastChar = [textField.text substringFromIndex:[textField.text length]];
[textField setText:lastChar];
NSLog(#"%#", lastChar);
} else {
updateTextField = YES;
}
}
Or something like that anyway...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length > 8) {
return NO;
}
return YES;
}

Solution for iPhone new file dialog keyboard

i want to let the user type in the name of a new file, so there are certain characters i want to prevent entry on. is there a special keyboard i can use or can i disable certain keys on the iphones keyboard.
is the answer to just run a regular expression on the input text and tell the user the filename is invalid (if so what would that regular expression be?)
ANSWER: (or what i ended up doing)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
BOOL valid;
//if the user has put in a space at the beginning
if ([string isEqualToString:#" "]){
if (range.location == 0){
valid = NO;
}
else{
valid = YES;
}
}
//otherwise test for alpha numeric
else{
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
valid = [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:#""];
}
//print the warning label
if (valid == NO){
[errorLabel setText:#"Invalid input"];
}
else{
[errorLabel setText:nil];
}
return valid;
}
You can implement the delegate method
For UITextField,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
For UITextview
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
and decide weather to append the entered characters or not.
You can implement the UITextFieldDelegate protocol and use textField:shouldChangeCharactersInRange:replacementString: to watch the text entry and prevent unwanted characters by returning NO.

Filtering characters entered into a UITextField

I have a UITextField in my application. I'd like to restrict the set of characters that can be can be entered into the field to a set that I have defined. I could filter the characters entered into the field when the text is committed using the UITextFieldDelegate method:
- (BOOL)textFieldShouldReturn:(UITextField*)textField
However, this gives the user a false impression as although restricted characters are removed from the final value, they were still visibly entered into the text field before pressing Return/Done/etc. What is the best approach that would prevent restricted characters appearing in the text field as they are selected on the keyboard?
Note: I am operating under the assumption that I have little control over which keys are provided by the iPhone keyboard(s). I am aware that I can switch between various keyboard implementations but am under the impression that I can't disable specific keys. This assumption may be incorrect.
I did as marcc suggested and it worked well. Sample implementation follows.
Note: Variable names were selected for brevity and do not reflect my coding standards:
...
myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"xyzXYZ"];
...
}
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered {
for (int i = 0; i < [textEntered length]; i++) {
unichar c = [textEntered characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
return NO;
}
}
return YES;
}
Look at textField:shouldChangeCharactersInRange
This method is called by the UITextFieldDelegate whenever new characters are typed or existing characters are deleted from the text field. You could return NO to not allow the change.
Here is one of the cleanest approaches to restricting characters entered in a UITextField. This approach allows the use of multiple predefined NSCharacterSets.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacters formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
[allowedCharacters formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){
return YES;
}
return NO;
}
Look at the UITextViewDelegate method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string.
It's exactly what you need.
This is what I use to restrict the user to uppercase A-Z. Adjust the regex variable according to taste:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* regex = #"[^A-Z]";
return ([string rangeOfString: regex
options:NSRegularExpressionSearch].location == NSNotFound);
};
How about this?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* regex = #"[^a-z]";
return ([[string lowercaseString] rangeOfString: regex
options:NSRegularExpressionSearch].location == NSNotFound);
};
Note:
I am making all characters to lower case [string lowercaseString] so that you don't need to write in regex for captial/small letters.
You could loop and keep checking if the UITextField.text property has changed once the DidBeginEditing method gets called. If it has, check the text and remove an bad characters.