2017-07-25 166 views
0

我正在使用以下textfield delegate验证用户条目。shouldChangeCharactersInRange行为异常

我们假设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 = @"$ "; 
} 
+0

什么是您的currentTotal –

+0

是30.00,双。 – hotspring

+0

将double转换为integerValue并检查一次 –

回答

3

您使用的方法是-textView:shouldChangeCharactersInRange:replacement。该应该意味着该行动即将完成,但尚未完成。因此,从文本字段获取值,您将获得旧值。

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

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

你能请说明与代码? – hotspring

1
-(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]; 
    } 

} 
+0

不要在'shouldChangeCharactersInRange'委托方法中设置'UIControlEventEditingChanged'事件。这是错误的。为什么每次文本字段的值将要改变时,你都会继续调用'addTarget'? – rmaddy

+0

@rmaddy,那你有什么建议?建议的解决方案工作'textFieldDidChange'被调用。 – hotspring

+0

在viewDidLoad中设置一次文本字段。 – rmaddy