我正在使用以下 textfield delegate
来验证用户输入。
假设 currentTotal
等于 30.00
美元,每当用户输入 两次
等于或大于 currentTotal
并且我正在尝试发出警报。
当我测试应用程序时,当用户输入 63
美元时,不会发生警报,但只要用户输入 630
美元就会发出警报。
tip
和 currentTotal
是 double
。
我做错了什么,有什么建议吗?
- (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 = @"$ ";
}
最佳答案
您使用的方法是-textView:shouldChangeCharactersInRange:replacement
。 应该 表示该操作即将完成,但尚未完成。因此从文本字段中获取值,您将获得旧值。
如果您想知道新值,您必须自己替换方法中的替换项(复制字符串值)。
NSString *newValue = [aTextField.text stringByReplacingCharactersInRange:range withString:string];
double tip = [newValue doubleValue]; // Where does your var tip comes from?
关于ios - shouldChangeCharactersInRange 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293977/