2017-07-25 60 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