ios - 无法使用退格键从 iOS 中的文本字段中删除字符

标签 ios objective-c uitextfield uitextfielddelegate

我正在为 UITextField 实现以下委托(delegate)方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

         NSString *integerPart = [textField.text componentsSeparatedByString:@"."][0];
         NSString *decimalPart = [textField.text componentsSeparatedByString:@"."][1];

         if ([integerPart length] > 8 || [decimalPart length] > 5) {
             return NO;//this clause is always called.
         }
...
}

我试图将在 textField 中输入的位数限制为 6。我遇到的问题是,如果我输入一个小数点后有 6 位的数字,然后尝试按我设备上的退格键来删除数字,或者需要在数字内部进行更正,我无法做到。

原因是,无论何时在我的代码中提到这一点,它都会注意到我已经输入了小数点后 6 位数字(这是正确的),因此,我的退格键输入无效。如何保持小数点后 6 位数字的限制,并允许在达到此限制后编辑数字?

最佳答案

我还没有机会对此进行测试,但根据 this answer ,当输入退格键时,字符串应该为空(这是有道理的)。所以你应该能够做到这一点。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

         // Always allow a backspace
         if ([string isEqualToString:@""]) {
              return YES;
         }

         // Otherwise check lengths
         NSString *integerPart = [textField.text componentsSeparatedByString:@"."][0];
         NSString *decimalPart = [textField.text componentsSeparatedByString:@"."][1];

         if ([integerPart length] > 8 || [decimalPart length] > 5) {
             return NO;//this clause is always called.
         }

         return YES;
}

关于ios - 无法使用退格键从 iOS 中的文本字段中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24832136/

相关文章:

objective-c - 保存首选项以显示或隐藏 NSStatusItem

iphone - Objective-C 中的 MySQL 命令

ios - 如何在 iOS Objective C 中指定约束?

iphone - 以正确的方式检测 UITextField 中的退格键

ios - 如何从 cellForRowAtIndexPath 获取 textField 上的边框线?

ios - objective-C : Weak attritube don't work as expected

ios - UITableView 的动画高度

ios - 展开/压缩 UICollectionView 中的所有 UICollectionView 单元格

ios - 如何检查 AVAudioPlayer 是否仍在运行?

ios - UITextField 在模拟器中更大