shouldChangeCharactersInRange逻辑

时间:2011-12-05 15:09:01

标签: ios

我似乎无法找出解决这个问题的最佳方法。当用户按小数点时,我希望它移动到下一个文本字段。我遇到的问题是它在下一个文本字段中显示小数,只有在我输入小数时才有效。我相信我理解为什么它只允许十进制是因为我开始if语句的方式,但我似乎无法找到最好的方法。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *decmial = @".";

    if ([textField.text isEqualToString:@"."])
    {
        if (octet1.text == decmial) {
            octet1.text = [octet1.text stringByReplacingOccurrencesOfString:decmial withString:@""];
            [octet1 isFirstResponder];
            [octet2 becomeFirstResponder];
        }
        else if (octet2.text == decmial) {
            octet2.text = [octet2.text stringByReplacingOccurrencesOfString:decmial withString:@""];
            [octet2 isFirstResponder];
            [octet3 becomeFirstResponder];
        }
        else if (octet3.text == decmial) {
            octet3.text = [octet3.text stringByReplacingOccurrencesOfString:decmial withString:@""];
            [octet3 isFirstResponder];
            [octet4 becomeFirstResponder];
        }  
        else if (octet4.text == decmial) {
            octet4.text = [octet4.text stringByReplacingOccurrencesOfString:decmial withString:@""];
            [octet4 isFirstResponder];
            [myBitMask becomeFirstResponder];
        } 
    }
    return YES;
}

1 个答案:

答案 0 :(得分:0)

目前,如果要修改的文本字段的整个内容完全是“。”,那么您只会执行任何操作。我假设您应该通过与替换字符串进行比较来测试用户是否输入了类型:

if ([string isEqualToString:@"."]) {

然后继续依次测试每个文本字段,而不考虑要修改的实际文本字段(传递给函数的文本字段)。你试着检查每一个,看看它是不是“。” (除非你没有,因为你正在使用==而不是isEqualToString),如果是,那么你用用户刚输入的内容替换整个字符串。确实很奇怪!

根据你对你想做什么的描述,如何:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *decmial = @".";

    if ([string isEqualToString:decmial])
    {
        textField.text = [textField.text stringByReplacingOccurrencesOfString:decmial withString:@""];

        if (textField == octet1) {
            [octet2 becomeFirstResponder];
        }
        else if (textField == octet2) {
            [octet3 becomeFirstResponder];
        }
        else if (textField == octet3) {
            [octet4 becomeFirstResponder];
        }  
        else if (textField == octet4) {
            [myBitMask becomeFirstResponder];
        } 

        // We've done the replacement ourselves and moved to the next field.  Don't allow the system to accept the change

        return NO;
    }

    // Default behavior

    return YES;
}