textField:shouldChangeCharactersInRange:replacementString:

我们两清 提交于 2019-11-28 11:28:00

问题


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) {
        charSet = [[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet] retain];
    }
    NSRange location = [string rangeOfCharacterFromSet:charSet];
    return (location.location == NSNotFound);
}

回答1:


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]


来源:https://stackoverflow.com/questions/7531834/textfieldshouldchangecharactersinrangereplacementstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!