Created
July 7, 2016 02:14
-
-
Save quangtqag/5572220fb21fefd487d7696be3bc39f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ObjC | |
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { | |
BOOL result = YES; | |
NSString *prospectiveText = [textField.text stringByReplacingCharactersInRange:range withString:string]; | |
if ([textField isEqual:self.numberTextField]) { | |
if (string.length > 0) { | |
NSCharacterSet *disallowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"].invertedSet; | |
BOOL replacementStringIsLegal = [string rangeOfCharacterFromSet:disallowedCharacterSet].location == NSNotFound; | |
BOOL resultingStringLengthIsLegal = prospectiveText.length <= 6; | |
NSScanner *scanner = [NSScanner scannerWithString:prospectiveText]; | |
BOOL resultingTextIsNumeric = [scanner scanDecimal:nil] && scanner.atEnd; | |
result = replacementStringIsLegal && | |
resultingStringLengthIsLegal && | |
resultingTextIsNumeric; | |
} | |
} | |
return result; | |
} | |
Swift | |
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { | |
var result = true | |
let prospectiveText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) | |
if textField == numberField { | |
if count(string) > 0 { | |
let disallowedCharacterSet = NSCharacterSet(charactersInString: "0123456789.-").invertedSet | |
let replacementStringIsLegal = string.rangeOfCharacterFromSet(disallowedCharacterSet) == nil | |
let resultingStringLengthIsLegal = count(prospectiveText) <= 6 | |
let scanner = NSScanner(string: prospectiveText) | |
let resultingTextIsNumeric = scanner.scanDecimal(nil) && scanner.atEnd | |
result = replacementStringIsLegal && | |
resultingStringLengthIsLegal && | |
resultingTextIsNumeric | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment