uitextfield how to parse the NSString - ios

I am new to iOS.
I have a UITextField where I am adding values like: 1234, 54678, 8976
In the method shouldChangeCharactersInRage i want to take everytime the nsstring after , .
Meaning if i am adding : 1234 in my NSString I want to have 1234
If I have 1234, 5 in my NSStringg i will only have 5
Here is the code I have so far:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *getNo=[textField.text stringByReplacingCharactersInRange:range withString:string];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\ .*?," options:0 error:NULL];
NSArray *matches = [regex matchesInString:getNo options:0 range:NSMakeRange(0, [getNo length])];
NSTextCheckingResult *match = [matches lastObject];
if (match!=nil){
getNo=#"";
}
The problem in this case is the fact that IN THE FOLLOWING CASE: 1234, 65 instead of having 65 in my getNo, I will have an empty object.
How to solve this?

Try this.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *textFieldString=[textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *subStrings = [textFieldString componentsSeparatedByString:#","];
NSString *lastNumberString = [subStrings lastObject];
NSString *trimmedString = [lastNumberString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
return YES;
}

Try this
NSArray *subStrings = [textFieldTextString componentsSeparatedByString:#","]; //this will returns array of strings separated by ,
double answer = [[subStrings lastObject] doubleValue];//get last value and type cast it

Related

Regex in iOS to limit a text field to only letters and single apostrophies

After a text field is returned I want to check if the text provided is valid. Valid means only letters or a single apostrophe, for names.
I'm pretty new to regular expressions. Is there a simple regular expression I can use for this check, or can someone point me towards some reading material where I can learn to compose a regular expression that will fit my needs?
You can do it like this, but you need to show an error in case the input is invalid.
- (BOOL)textFieldShouldEndEditing:(UITextField *)aTextField
{
NSString *const regularExpression = #"^[a-zA-Z']+$";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression
options:kNilOptions
error:&error];
if (error) {
// Handle error
}
NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString
options:0
range:NSMakeRange(0, [aString length])];
return numberOfMatches > 0;
}
The regx should be
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
you can use
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == emailid) {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
;
return [string isEqualToString:filtered];
}
}
You can use the function that checks whether the input should be inserted or not and restrict the characters there. Since your restriction is fairly simple there is no need of regular expressions and you can use characters sets.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacters addCharactersInString:#"'"];
if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){
return YES;
}
return NO;
}

Remove hashtag from string after typing, store it in a different string

I am trying to create functionality where if the user typed in a hashtag it would remove it from the textview and store it in a string. This would be triggered by typing a hashtag and hitting space after it.
What's a good way to go about this?
I figured out how to get the word out thats hash tagged. Just need a way to remove it from my display. and leave the rest of the text.
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"(#(\\w+))"
options:0
error:&error];
NSArray * matches = [regex matchesInString:stringCheck options:0 range:NSMakeRange(0, [stringCheck length])];
for (NSTextCheckingResult* match in matches ) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [stringCheck substringWithRange:wordRange];
NSLog(#"%#", word);
}
Is this what you're looking for?
set textView delegate to your .m and .h files
<UITextFieldDelegate> and [self.textField setDelegate:self];
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(#"string: %#", string);
if ([string isEqualToString:#" "])
{
NSString *stringCheck = textField.text;
NSError *error;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"(#(\\w+))"
options:0
error:&error];
NSArray * matches = [regex matchesInString:stringCheck options:0 range:NSMakeRange(0, [stringCheck length])];
for (NSTextCheckingResult* match in matches ) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [stringCheck substringWithRange:wordRange];
NSLog(#"%#", word);
[self.textField setText:#""];
}
}
return YES;
}

Editing textfield after "endEdit" with ShouldChangeCharactersInRange implemented

I have the following code implemented to restrict my user to enter in more than 2 decimal points and places after they have entered the first one. Users can still edit the textfield as long as they don't "leave" or "endEdit" the textfield. However, once they leave the textfield and go back, the textfield is not editable. How can I solve this problem?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.SalesAmounttext)
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = #"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
return NO;
}
return YES;
}
All I had to do was add in the clearsOnInsertion code and everything works! Thanks to #Wain
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.SalesAmounttext)
{
textField.clearsOnInsertion=YES ; // HERE
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = #"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
return NO;
}
return YES;
}
Your logic places very tight restrictions on the user so any arbitrary edit will not be permitted. From a user standpoint that will probably be quite confusing so good options would be:
Set clearsOnInsertion when the text field is created so that each edit is a fresh start
Alert the user about invalid edits
Allow each edit and then format at the end of editing and alert the user to any issue then

Allow only 2 whitespace in text

I have a UITextField and I want to allow user enter in this field maximum 2 whitespace. How I can do it?
I think I need to check something here:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {}
But what to check? I have searched the web, but nothing found.
You want to use a regular expression for this. The expression \s\s+ means two or more spaces, carriage returns or tabs.
NSString *text = textField.text;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
#"(\s\s+)" options:0 error:nil];
[regex replaceMatchesInString:str options:0 range:NSMakeRange(0, [str length]) withTemplate:#" "];
textField.text = text;
This will return how many spaces there are in the string
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
int numberOfSpaces = [[textField.text componentsSeparatedByString:#" "] count];
if (numberOfSpace > 2) {
//notify user that he/she has too many spaces
}
}
Also you seem new to iOS. Don't forget to set your view controller as a UITextField delegate.

how to validation and format input string to 1234567890 to 123-456-7890

I have to format input string as phone number.For i am using
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
if (string.length==3||string.length==7) {
filtered =[filtered stringByAppendingString:#"-"];
}
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
here
#define NUMBERS_ONLY #"1234567890-"
#define CHARACTER_LIMIT 12
but its not editing back.
Please give some ideas
The method you're using is a UITextFieldDelegate method that determines whether or not to allow a change to the text field - given the range and replacement text, should the change be made (YES or NO).
You're trying to format a string while it is being typed - for this you'll also need to update the value of the textField.text property. This could be done in the same method while returning a "NO" afterwards.
For validation,
- (BOOL) isValidPhoneNumber
{
NSString *numberRegex = #"(([+]{1}|[0]{2}){0,1}+[0]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",numberRegex];
return [numberTest evaluateWithObject:self.inputString];
}
You can use this for formatting the string,
self.inputString = #"1234567890"
NSArray *stringComponents = [NSArray arrayWithObjects:[self.inputString substringWithRange:NSMakeRange(0, 3)],
[self.inputString substringWithRange:NSMakeRange(3, 3)],
[self.inputString substringWithRange:NSMakeRange(6, [self.inputString length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"%#-%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];

Resources