How to find a particular text in UITextField? - objective-c

In my iPhone app I have a UITextField ans text field value is being taken into an NSString, I want to find if a particular character " is typed in that
How can I do that?
UITextField *textField;
NSString *String=textField.text;
-(IBAction)FindCharecter:(id)sender
{
// if String Contain ",then i wish to print #"Found symbol"
}

UITextField *textField;
NSString *string=textField.text;
if ([string rangeOfString:#"\""].location == NSNotFound) {
NSLog(#"string does not \"");
} else {
NSLog(#"string contains \"");
}
check this

Try This:
-(IBAction)FindCharecter:(id)sender
{
// if String Contain ",then i wish to print #"Found symbol"
if ([String rangeOfString:#"\""].location != NSNotFound) {
NSLog(#"Found");
}
else{
NSLog(#"Not Found");
}
}

Implement the following delegate of UITextField
-(NSString *)ValidateSearchString:(NSString *) aString{
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"YourString"] invertedSet];
if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
return #"Not Found";
}
return #"Found";;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog("particular character %#",[self ValidateSearchString:string]);
// string will contain the particular character typed;
return YES;
}

You need to confirm and implement UITextFieldDelegate protocol.
1) If you want to check for a pattern on the go (when user typing itself), you need to implement
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
2) If you want to check when user completed typing, you may want to implement
- (void)textFieldDidEndEditing:(UITextField *)textField
Now to do the actual comparison process
if([textFieldString rangeOfString:#"YOUR_COMPARISON_STRING"].location == NSNotFound){
//your pattern is not typed yet
}else{
//There it is..
}

You can use shouldChangeCharactersInRange delegate method for this.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#"\""])
{
NSLog(#"Entered \" ");
}
}
Or you can use: rangeOfString of NSString class.
if ([textField.text rangeOfString:#"\""].location == NSNotFound)
{
NSLog(#"Entered \" ");
}
For reference:
textField:shouldChangeCharactersInRange:replacementString:
Asks the delegate if the specified text should be changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Parameters
textField
The text field containing the text.
range
The range of characters to be replaced
string
The replacement string.
Return Value
YES if the specified text range should be replaced; otherwise, NO to
keep the old text. Discussion
The text field calls this method whenever the user types a new
character in the text field or deletes an existing character.
Availability
Available in iOS 2.0 and later.
UITextFieldDelegate
rangeOfString:
Finds and returns the range of the first occurrence of a given string
within the receiver.
- (NSRange)rangeOfString:(NSString *)aString
Parameters
aString
The string to search for. This value must not be nil.
Important: Raises an NSInvalidArgumentException if aString is nil.
Return Value
An NSRange structure giving the location and length in the receiver of
the first occurrence of aString. Returns {NSNotFound, 0} if aString is
not found or is empty (#"").
Discussion
Invokes rangeOfString:options: with no options.
This method detects all invalid ranges (including those with negative
lengths). For applications linked against OS X v10.6 and later, this
error causes an exception; for applications linked against earlier
releases, this error causes a warning, which is displayed just once
per application execution. Availability
Declared In NSString.h
Declared In UITextField.h
NSString Class

Related

How to set max string length for UIAlertView text field

How can I set the max string length for a textfield created within a UIAlertView? I am using Xcode 4.5 and building the app on 10.8 (OS X) Currently I have UIAlertView that launches when the user clicks a button. The user will scan their RFID badge, and I want the input textfield of the UIAlertView to be limited to 10 (ten) characters so the user can't fudge association process.
You can check the length of the text in the delegate method of the textField:
textField:shouldChangeCharactersInRange:replacementString:
And return NO if you don't want to change.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length - range.length + string.length > 10) {
return NO;
}
return YES;
}
Looks like the above answer is almost right.
When typing single characters, range.length (for this method) appears to always be zero, while the location increments.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(#"Range: %#", NSStringFromRange(range));
return ( range.location < 10 );
}
edit: length would probably be longer if you doing something other than single-character typing, i.e. pasting a line, etc.

How can I force NSTextField to only allow numbers?

In Interface Builder I’ve created a textfield and stuck an NSNumberFormatter into the cell. However, the user can still type text into the textfield. Is there any way to restrict the input to numbers only using interface builder? I thought that was the point of the NSNumberFormatter.
Every formatter has this method:
- (BOOL) getObjectValue: (id*) object forString: (NSString*) string
errorDescription: (NSError**) error;
This is valid for every formatter.
If the string is not valid it returns false and the object passed as argument (dereferenced) will be nil.
So instead of dropping a number formatter to the text field, use your own formatter as instance variable.Observe the text field implementing the delegate protocol so that at every change of the text you can be notified.
Then invoke this method:
NSNumber* number;
BOOL success=[formatter getObjectValue: &number forString: [myTextField stringValue] errorDescription:nil];
At this point if success is false (or check if number is nil), there is an invalid string in the text field, so do the action that is more appropriate for you (maybe delete the entire string, or display 0.0 as value).
There is also another method:
- (BOOL) isPartialStringValid : (NSString*) partialString: (NSString*) partialString
errorDescription: (NSString*) error;
This way you can know if a partial string is valid.For example with the scientific notation "1e" is not valid, but is partially valid because the user may add 1 and it will become "1e1".
Create an NSNumberFormatter subclass and put this in the implementation. In your code, set the YKKNumberFormatter as the formatter for the NSTextField/UITextField.
#implementation YKKNumberFormatter
- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error {
// Make sure we clear newString and error to ensure old values aren't being used
if (newString) { *newString = nil;}
if (error) {*error = nil;}
static NSCharacterSet *nonDecimalCharacters = nil;
if (nonDecimalCharacters == nil) {
nonDecimalCharacters = [[[NSCharacterSet decimalDigitCharacterSet] invertedSet] retain];
}
if ([partialString length] == 0) {
return YES; // The empty string is okay (the user might just be deleting everything and starting over)
} else if ([partialString rangeOfCharacterFromSet:nonDecimalCharacters].location != NSNotFound) {
return NO; // Non-decimal characters aren't cool!
}
return YES;
}
#end

Knowing the complete changed string in textField:shouldChangeCharactersInRange:replacementString:

I just asked a question about how to monitor changes to a UITextField and received this response :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacementStr {
// Enable "Next" if you like what's entered in the replacementStr
}
This works, but the replacement string is not the whole string, just what it is adding. How can I get the whole string? My objective is to see if the string in the text field is blank or equal to a certain number (in different scenarios).
Please note that the outlet to the text field doesn't work in this case, because this method is being called before the text in the field changes.
NSString * proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:replacementString];
Swift Version
In Swift We need to cast textField's text to NSString. The following can be useful:
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
// [textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
NSLog(#"%#",searchStr);
return YES;
}

how to restrict special characters in UITextField in iPad?

In my iPad app. I have one UITextField. User would enter some value in that text field. This value has to be Alpha Numeric. I want to show an alert to the user if he/she enters any special character.
How can I do it? What should be the condition for alert?
Any help would be highly appreciated.
Thanks and regards,
PC
Implement textField:shouldChangeCharactersInRange:replacementString: in the delegate, check the replacement string for special characters, and disallow the replacement if you detect any.
The easiest way to check for non-alphanumerics is as follows:
if ([replacementString rangeOfCharacterFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]].location != NSNotFound) {
// There are non-alphanumeric characters in the replacement string
}
You can do it as :-
#define ACCEPTABLE_CHARECTERS #" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];
if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1)
return NO;
else
return YES;
}

Limit text field length

Please tell me how I can set the range of a text field to a maximum of six and minimum of one.
Set self as textfield's delegate and implement this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (newString.length < 1) {
// too short
} else if (newString.length > 6) {
// too long
}
return YES;
}
I'd suggest you to have a UILabel that will say in red text that text is too short or too long. Just preventing user from typing into textfield when they reach 6 chars or deleting last character when they change their mind is a very bad user experience.
Implement the delegate method textField:shouldReplaceCharactersInRange:replacementString: and have your implementation return NO if the resulting string would fall outside of your constraints.