实现shouldChangeCharactersInRange方法时,Backspace不工作 - iPhone Dev

时间:2010-04-29 14:15:51

标签: iphone objective-c

问题...我有一串允许的字符“0123456789”。如何从键盘允许退格...当我从下面实现代码时...退格键不再有效......我该如何解决这个问题?

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

    return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);

}

4 个答案:

答案 0 :(得分:21)

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

    if (range.length == 1){
        return YES;
    }else{
        return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
    }


}

答案 1 :(得分:15)

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string length] == 0) 
        return YES; 

    NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    string = [[string componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:@""]; 
    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string]; 

    return NO; 
}

这应该可以一次删除/剪切多个字符以及粘贴。更正欢迎。唯一已知的问题是,当你在文本字段的中间编辑时,光标会被发送到结尾(因为它返回NO) - 我想你必须use a UITextView to fix that

答案 2 :(得分:1)

NSCharacterSet *theNonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];


        if (range.length == 1){
            return YES;
        }else if(textField.text.length < ZipcodeTextLength)
        {
            return ([string stringByTrimmingCharactersInSet:theNonNumberSet].length > 0);
        }
        else
            return NO;
  

这将允许Numbers和Backspace,您也可以限制文本长度。

答案 3 :(得分:0)

这是我的一个实现。也许它适合你。

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

for(UIView *view in _chooseUsernameDialog.subviews) {
    if([view isKindOfClass:[UIButton class]]) {
        int realLength;

        const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
        int isBackSpace = strcmp(_char, "\b");

        if (isBackSpace == -8) {
            // is backspace
            realLength = [textField.text length] - 1 ;
        }
        else
        {
            realLength = [textField.text length] + 1;
        }

        NSLog(@"%d", realLength );

        if(realLength < 4)
        {
            //too short

        }
        else{

            //long enough
        }
    }
}

return !([[textField text] length] + (string.length - range.length) > 13);
}