【问题标题】:shouldChangeCharactersInRange behaves strangeshouldChangeCharactersInRange 的行为很奇怪
【发布时间】:2017-07-25 04:31:14
【问题描述】:

我正在使用以下textfield delegate 来验证用户输入。

让我们假设currentTotal 等于30.00 美元,并且每当用户输入two times 等于或大于currentTotal 时,我正在尝试发出警报。

当我在测试应用程序时,当用户输入63 美元时,不会发生警报,​​但只要用户输入630 美元就会发出警报。

tipcurrentTotaldouble

我做错了什么,有什么建议吗?

- (BOOL)textField:(UITextField *)aTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{    
    if ([aTextField.text containsString:@"$"])
    {
        tip = [[aTextField.text stringByReplacingOccurrencesOfString:@"$" withString:@""] doubleValue];
    }
    else
    {
        tip = [aTextField.text doubleValue];
    }

    if(tip > currentTotal *2)
    {
      [self presentViewController:[AppConstant oneButtonDisplayAlert:@"Error" withMessage:@"Please enter valid tip"] animated:YES completion:nil];
    }

    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.tipTF.text = @"$ ";
}

【问题讨论】:

  • 你的当前总数是多少
  • 30.00,双倍。
  • 将 double 转换为 integerValue 并检查一次
  • 我需要加倍。当我调试时,即使在文本字段上我看到63,但在委托方法中我看到tip 值是6。当我添加一个数字使其成为630 时,我看到提示值为63,然后它会发出警报。

标签: ios objective-c uitextfield


【解决方案1】:

您使用的方法是-textView:shouldChangeCharactersInRange:replacementshould 表示动作即将完成,但尚未完成。因此,从文本字段中获取值,您将获得旧值。

如果您想知道新值,您必须自己替换方法中的替换(复制字符串值)。

NSString *newValue = [aTextField.text stringByReplacingCharactersInRange:range withString:string];
double tip = [newValue doubleValue]; // Where does your var tip comes from?

【讨论】:

    【解决方案2】:
    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        if (textField == self.tipTF)
        {
            if (self.tipTF.text && self.tipTF.text.length > 0) {
                [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
            }
        }
        return YES;
    }
    
    -(void)textFieldDidChange :(UITextField *)theTextField{
        NSLog( @"text changed: %@", theTextField.text);
        double tip;
        if ([theTextField.text containsString:@"$"])
        {
            tip = [[theTextField.text stringByReplacingOccurrencesOfString:@"$" withString:@""] doubleValue];
        }else {
            tip = [theTextField.text doubleValue];
        }
    
        if (tip > currentTotal *2) {
            [self presentViewController:[AppConstant oneButtonDisplayAlert:@"Error" withMessage:@"Please enter valid tip"] animated:YES completion:nil];
        }
    
    }
    

    【讨论】:

    • 不要在shouldChangeCharactersInRange委托方法中设置UIControlEventEditingChanged事件。那是错误的。为什么每次文本字段的值即将更改时,您仍要继续调用addTarget
    • @rmaddy,那你有什么建议?提议的解决方案有效textFieldDidChange 正在被调用。
    • 在 viewDidLoad 中设置一次文本字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    相关资源
    最近更新 更多