【问题标题】:Unable to use backspace key to delete a character from a textfield in iOS无法使用退格键从 iOS 的文本字段中删除字符
【发布时间】:2014-07-18 19:10:17
【问题描述】:

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

- (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 位的限制,并允许在达到此限制后编辑数字?

【问题讨论】:

    标签: ios objective-c uitextfield uitextfielddelegate


    【解决方案1】:

    我没有机会对此进行测试,但根据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;
    }
    

    【讨论】:

      【解决方案2】:
           //Construct the new string with new input
           NSString* newText = [textField.text stringByReplacingCharactersInRange:range
                                                                 withString:text];
      
           NSString *integerPart = [newText componentsSeparatedByString:@"."][0];
           NSString *decimalPart = [newText componentsSeparatedByString:@"."][1];
      
           if ([integerPart length] > 8 || [decimalPart length] > 5) {
               return NO;//this clause is always called.
           }
      

      我相信这就是您所需要的。这将构建将显示在文本字段中的新字符串,您可以评估该字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-26
        • 1970-01-01
        • 2013-06-05
        • 2014-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多