I have a quick question that I can’t find anywhere. I am limiting my text field to just numbers, decimals, and the negative sign. But in doing so, I turned off the return key. Anyone know the unichar number for iOS’s return key? I thought it was thirteen but that is not working.
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger lengthOfString = string.length;
for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++)
{
unichar character = [string characterAtIndex:loopIndex];
if (character < 45) return NO; //45 - 57 we want
if (character > 57) return NO; // -./0123456789
if (character == 47) return NO; //47 we dont want, it is
// if (character == 36) return YES
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
}
You might have some other reason to inspect the input. (I think comparing to ‘\n’ works), but this might be even better:
Edit
A more thorough treatment of handling floating point input might look like this. The key ideas are to build a candidate string with the proposed replacement, then test the whole string for syntactic validity. This way you can handle the user pasting in new text at some arbitrary position without touching the code. Regex is just a compact/quick way to specify syntax, you can put your own method in the validator.
(I guessed that you might want to handle a minus sign as not literally part of the input, but rather an indicator that a negative number is desired. Also assumed that the length limitation is for significant digits, not simply total chars)