开发者

textField:shouldChangeCharactersInRange:replacementString:

开发者 https://www.devze.com 2023-04-08 12:40 出处:网络
How can I correct this code. I want only numbers and range should be not exceed to 10. My code is - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementSt

How can I correct this code. I want only numbers and range should be not exceed to 10. My code is

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 10) ? NO : YES;

    static NSCharacterSet *charSet = nil;
    if(!charSet) {
     开发者_StackOverflow社区   charSet = [[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet] retain];
    }
    NSRange location = [string rangeOfCharacterFromSet:charSet];
    return (location.location == NSNotFound);
}


The problem here is that anything after the first return is not executed.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 10) ? NO : YES;
    // unreachable!

So you are just checking the length but not whether the input is numerical. Change this line:

return (newLength > 10) ? NO : YES;

with this one:

if (newLength > 10) return NO;

and it should work. You can also optionally change this:

[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]

with this:

[NSCharacterSet decimalDigitCharacterSet]
0

精彩评论

暂无评论...
验证码 换一张
取 消