determine if a string is a number with NSScanner - objective-c

i'm trying to find out if my string contains any floatValue, and resign the first responder if it's the case, if it's not, the textfield keyboard should stay on screen.
This code always hides the keyboard, even if it's not a floatValue : do you know how to make it work?
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSScanner *scan = [NSScanner scannerWithString:[textField text]];
if ([scan scanFloat:NULL]){
[password resignFirstResponder];
[passwordLength resignFirstResponder];
return YES;
} else {
return NO;
}
}
Also, i haven't tried with loops but this is a beginning, if you have any idea :
BOOL doesStringContain(NSString* string, NSString* string2){
for (int i=0; i<[string length]; i++) {
NSString* chr = [string substringWithRange:NSMakeRange(i, 1)];
for (int j=0; j<[string2 length]; j++){
if([chr isEqualToString:j])
return TRUE;
}
}
return FALSE;
}
Thanks a lot

NSScanner will expect that your float be at the beginning of your string. So to combat that we use setCharactersToBeStripped.
setCharactersToBeStripped will filter out all non-numeric non-period characters from the string so that all you're left with to scan is the number that you're looking for.
NSScanner will match int values (without the .) as well as it will equate an int 123 to 123.00000.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSScanner *scan = [NSScanner scannerWithString:[textField text]];
[scan setCharactersToBeSkipped:[[NSCharacterSet characterSetWithCharactersInString:#"1234567890."] invertedSet]];
float f;
if ([scan scanFloat:&f]){
NSLog(#"Scanned a float %f",f);
[textField resignFirstResponder];
return YES;
} else {
NSLog(#"Did not scan a float");
return NO;
}
}
If you want to check if there are non-numeric characters vs only numerics then try :
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSCharacterSet *withFloats = [NSCharacterSet characterSetWithCharactersInString:#"0123456789."];
NSCharacterSet *withoutFloats = [NSCharacterSet decimalDigitCharacterSet];
// Change withFloats <-> withoutFloats depending on your need
NSString *newString = [[textField.text componentsSeparatedByCharactersInSet:withFloats] componentsJoinedByString:#""];
NSLog(#"newString %#", newString);
if ([newString isEqualToString:#""]){
NSLog(#"Scanned a numeric");
[textField resignFirstResponder];
return YES;
} else {
NSLog(#"Did not scan a numeric");
return NO;
}
}

You are implementing the wrong delegate method. textFieldShouldReturn: is called when the user hits the return key. (Not when control is trying to "return from" the field, in case that's what you were thinking.)
You should implement textFieldShouldEndEditing: instead. That is where you can (try to) stop the text field from losing first responder status, and keep the keyboard up. Just check the text like you are doing, and return YES or NO (let the system update first responder status).
If you want the return key to dismiss the keyboard if input is valid, you should call endEditing: there. Like this:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return [textField endEditing:NO];
}
The NO parameter means don't force it, basically allowing your textFieldShouldEndEditing: code to check the text first. (You should always call endEditing: if you can, rather than resignFirstResponder.)
Note that, for various reasons, the text field might be forced to give up first responder status anyway, so even if you're validating input in this way, be prepared to validate it again before you save it to disk or send it over the network or whatever you want to do with it.

Related

Prevent Users from Entering Multiple Decimals In A String

I am doing a button calculator app (still) in which users press a button, I store a value into a string to display in a text box, and then convert into floats when the user enters the = button.
Works great for the most part, except I cannot figure out how to prevent users from entering more than one decimal in a single string. I thought about passing it to a BOOL method, but none of my class materials cover methods at all.
I looked at this Stack overflow question, but trying to amend the code for my own just resulted in a whole bunch of errors. Does anyone have any advice?
-(IBAction) decimal
{
NSString *decVal =#".";
NSRange range = [decVal rangeOfString:#"."];
if (range.location==NSNotFound)
{
display.text = [display.text stringByAppendingString:decVal];
}
else
{
NSLog(#"You can't enter more than one decimal");
}
}
-(IBAction) decimal
{
static NSString *decVal =#".";
NSRange range = [display.text rangeOfString:decVal];
if (NSNotFound == range.location)
{
display.text = [display.text stringByAppendingString:decVal];
}
else
{
NSLog(#"You can't enter more than one decimal");
}
}
You have missed in one string. [decVal rangeOfString:#"."] will always return range {0,1}.
One way to handle this would be to set the delegate of the text field/view and then implement shouldChangeCharactersInRange in the delegate.
For example, you could do something like this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
BOOL hasPeriod = ([textField.text rangeOfString:#"."].location != NSNotFound);
BOOL removingPeriod = ([[textField.text substringWithRange:range]
rangeOfString:#"."].location != NSNotFound);
BOOL addingPeriod = ([string rangeOfString:#"."].location != NSNotFound);
return (hasPeriod && addingPeriod && !removingPeriod) ? NO : YES;
}
This won't throw an error. It just won't allow a second period. You could easily add in the error message, though.

How can I check the value of a string obtained via scripting?

My Mac app gets 2 string values from another app via scripting. Under certain conditions, the sender supplies "0-1". I need to detect this and blank the text box that displays it. The following, which only shows code for the second string, works in the debugger, but not when run outside it.
- (void)controlTextDidChange:(NSNotification *)notification
{
// there was a change in a text control
int tmpInt2 = 0;
NSMutableString *tmp2 = [NSMutableString stringWithString:[inputTextField2 stringValue]];
//NSLog(#"text box changed. value: %i", val);
if ([tmp2 length] > 3)
{
tmp2 = [NSMutableString stringWithString:[tmp2 substringToIndex:[tmp2 length] - 1]];
[inputTextField2 setStringValue:tmp2];
}
if ([tmp2 length] == 3)
{
tmpInt2 = [tmp2 intValue];
if (tmpInt2 > 360 || tmpInt2 < 0 || [tmp2 isEqualToString:#"0-1"])
{
//[self showAlert:#"Heading must be between 000 and 360"];
[inputTextField2 setStringValue:#""];
//[inputTextField2 setBackgroundColor:[NSColor yellowColor]];
[tmp2 setString:#""];
}
}
if ([[inputTextField2 stringValue] rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
{
NSLog(#"This is not a positive integer");
//NSMutableString *strippedString = [NSMutableString stringWithCapacity:tmp.length];
[inputTextField2 setStringValue:#""];
//[[inputTextField2 cell] setBackgroundColor:[NSColor yellowColor]];
[tmp2 setString:#""];
}
/*
if ([tmp2 isEqualToString:#"0-1"])
{
[inputTextField2 setStringValue:#""];
[tmp2 setString:#""];
}
*/
if ([tmp2 rangeOfString:#"-"].location == NSNotFound) {
NSLog(#"string does not contain 0-1");
} else {
NSLog(#"string contains 0-1!");
[inputTextField2 setStringValue:#""];
[tmp2 setString:#""];
}
}
You should look into #trojanfoe's suggestion of using NSFormatter or one of its pre-defined subclasses. However you appear to misunderstand the purpose of NSMutableString, so I offer the following version of your code with some comments embedded. The text field used for the test was given a placeholder value of "Enter Heading", and it is assumed ARC is enabled. Modern property access syntax is used (object.property). HTH.
- (void)controlTextDidChange:(NSNotification *)notification
{
// there was a change in a text control
NSTextField *inputTextField = notification.object; // get the field
NSTextFieldCell *fieldCell = inputTextField.cell; // and its cell - we use the placeholder text for feedback in this sample
fieldCell.placeholderString = #"Enter heading"; // user has typed, restore default message
NSString *contents = inputTextField.stringValue; // an NSMutableString is not required, you never mutate this string
NSUInteger length = contents.length;
if (length > 3)
{
// remove last character - did you mean to truncate to three characters?
inputTextField.stringValue = [contents substringToIndex:length - 1];
}
else if (length == 3)
{
int tmpInt = contents.intValue;
if (tmpInt > 360 || tmpInt < 0 || [contents isEqualToString:#"0-1"])
{
fieldCell.placeholderString = #"Heading must be between 000 and 360"; // inform user why field was blanked
inputTextField.stringValue = #"";
}
}
else if ([contents rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
{
// you might want different logic here
// if a user types "12Y" you delete everything, deleting just the "Y" might be more friendly
// ("Y" picked as an example as it could be a miss hit for the 6 or 7 keys)
fieldCell.placeholderString = #"Enter a positive integer"; // inform user why field was blanked
inputTextField.stringValue = #"";
}
}
Addendum - Comment Followup
Exactly what inputs you are expecting and what you wish to do with them is unclear. The first if just removes the last character from strings longer than 3 without doing any other checks. However I may have misinterpreted your intentions here, you have have intended to continue processing after that first if, e.g. something like:
...
if (length > 3)
{
// remove last character - did you mean to truncate to three characters?
contents = [contents substringToIndex:length - 1];
length -= 1;
}
if (length == 3)
{
...
Which means if your input is longer than 3 characters you remove the last (did you not want to simply truncate to 3? If so just change those two lines of code to do so) and then you continue with the following if/else.

How to find a particular text in UITextField?

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

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

Make portion of UITextView undeletable

I have a UITextView and need to make a specific portion un-deletable. Its the first 10 characters of the views text.
I just want it so that if the user is tapping the delete key on the keyboard it simply stops when it reaches say the 10th character in.
Edit
Let me go into a bit more detail.
Let's say the prefix is '123456789:'. I want to be able to type anywhere after this prefix, it can't be editable at all though, so '123456789:' shouldn't not be altered at all. Fichek's answer does this perfectly, however the prefix isn't always there, so how can I detect when it isn't in the textview? I thought the if statement did this but it seems not to.
You can use the delegate method textView:shouldChangeTextInRange:replacementText: To tell the text view whether to accept the delete or not.
As the documentation says:
range : The current selection range. If the length of the range is 0, range reflects the current insertion point. If the user presses the Delete key, the length of the range is 1 and an empty string object replaces that single character.
Edit
Here is an implementation where the user can't delete the the first ten characters. But he will be able to insert characters there.
- (BOOL)textView:(UITextView *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.length==1 && string.length == 0) {
// Deleting text
if (range.location <= 9) {
return NO;
}
}
return YES;
}
Here is an implementation where he can't modify the first ten characters at all.
- (BOOL)textView:(UITextView *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location <= 9) {
return NO;
}
return YES;
}
sch's last edit makes a decent answer, but I want to offer a slightly more flexible approach.
You have to keep in mind the copy/paste system. User might select all the text in text field and try to paste in the entire value which might be perfectly acceptable, but if (range.location <= 9) { return NO; } will reject it. The way I'd do it is put together a string that would be a result of successful edit and then check if that string would start with your desired prefix.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *resultString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSLog(#"resulting string would be: %#", resultString);
NSString *prefixString = #"blabla";
NSRange prefixStringRange = [resultString rangeOfString:prefixString];
if (prefixStringRange.location == 0) {
// prefix found at the beginning of result string
return YES;
}
return NO;
}
Edit: if you want to check if the current string in text field starts with the prefix, you can use rangeOfString: the same way:
NSRange prefixRange = [textField.text rangeOfString:prefixString];
if (prefixRange.location == 0) {
// prefix found at the beginning of text field
}
for a complete solution you need to handle several cases, including the cut and paste operations that may start in the uneditable part and extend into the part which the user can edit. I added a variable to control whether or not an operation that includes the uneditable part but extends into the editable part, is valid or not. If valid, the range is adjusted to only affect the editable part.
// if a nil is returned, the change is NOT allowed
- (NSString *)allowChangesToTextView:(UITextView *)textView inRange:(NSRange)changeRange withReplacementText:(NSString *)text
immutableUpTo:(NSInteger)lastReadOnlyChar adjustRangeForEdits:(BOOL)adjustRangeForEdits;
{
NSString *resultString = #"";
NSString *currentText = textView.text;
NSInteger textLength = [currentText length];
// if trying to edit the first part, possibly prevent it.
if (changeRange.location <= lastReadOnlyChar)
{
// handle typing or backspace in protected range.
if (changeRange.length <= 1)
{
return nil;
}
// handle all edits solely in protected range
if ( (changeRange.location + changeRange.length) <= lastReadOnlyChar)
{
return nil;
}
// if the user wants to completely prevent edits that extend into the
// read only substring, return no
if (!adjustRangeForEdits)
{
return nil;
}
// the range includes read only part but extends into editable part.
// adjust the range so that it does not include the read only portion.
NSInteger prevLastChar = changeRange.location + changeRange.length - 1;
NSRange newRange = NSMakeRange(lastReadOnlyChar + 1, prevLastChar - (lastReadOnlyChar + 1) + 1);
resultString = [textView.text stringByReplacingCharactersInRange:newRange withString:text];
return resultString;
}
// the range does not include the immutable part. Make the change and return the string
resultString = [currentText stringByReplacingCharactersInRange:changeRange withString:text];
return resultString;
}
and this is how it gets called from the text view delegate method:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// did the user press enter?
if ([text isEqualToString:#"\n"])
{
[textView resignFirstResponder];
return NO;
}
NSInteger endOfReadOnlyText = [self.spotTextLastSet length] - 1;
NSString *newText = [self allowChangesToTextView:textView inRange:range withReplacementText:text
immutableUpTo:endOfReadOnlyText adjustRangeForEdits:YES];
if (newText == nil)
{
// do not allow!
[TipScreen showTipTitle:#"Information" message:#"The first part of the text is not editable. Please add your comments at the end."
ForScreen:#"editWarning"];
return NO;
}
// lets handle the edits ourselves since we got the result string.
textView.scrollEnabled = NO;
textView.text = newText;
// move the cursor to change range start + length of replacement text
NSInteger newCursorPos = range.location + [text length];
textView.selectedRange = NSMakeRange(newCursorPos, 0);
textView.scrollEnabled = YES;
return NO;
}