文本框:shouldChangeCharactersInRange:replacementString: [英] textField:shouldChangeCharactersInRange:replacementString:

查看:130
本文介绍了文本框:shouldChangeCharactersInRange:replacementString:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更正此代码。我只想要数字和范围不应超过10.
我的代码是

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);
}


推荐答案

这里的问题是什么在第一个返回之后没有执行。

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;

这一个:

if (newLength > 10) return NO;

它应该有效。您也可以选择更改此项:

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

[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]

这个:

[NSCharacterSet decimalDigitCharacterSet]

这篇关于文本框:shouldChangeCharactersInRange:replacementString:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆