【问题标题】:Require a UITextField to take 5 digits [duplicate]要求 UITextField 取 5 位数字 [重复]
【发布时间】:2015-03-06 14:05:54
【问题描述】:

我设置了一个 UITextField 来显示数字键盘。如何要求用户准确输入 5 位数字?

我四处寻找,发现我应该使用 shouldChangeCharactersInRange,但我不太了解如何实现它。

【问题讨论】:

    标签: objective-c uitextfield uitextfielddelegate


    【解决方案1】:

    当用户离开文本字段/使用按钮验证时,我会使用它

    if ([myTextField.text length] != 5){
    
    //Show alert or some other warning, like a red text
    
    }else{
     //Authorized text, proceed with whatever you are doing
    }
    

    现在,如果您想在用户键入时计算字符数,您可以在viewDidLoad 中使用

    [myTextfield addTarget: self action@selector(textfieldDidChange:) forControlEvents:UIControlEventsEditingChanged]
    
    -(void)textFieldDidChange:(UITextField*)theTextField{
     //This happens every time the textfield changes
    }
    

    如果您需要更多帮助,请务必在 cmets 中提问:)

    【讨论】:

    • 你说得对,我编辑的方式不同,所以它仍然尽可能清晰。向你竖起大拇指
    • 谢谢@PaulR 和 Zil 这就是我想要的。
    • 我不明白为什么你们都写长度而不是长度@PaulR
    • 这是一个错字,然后可能只是在这些 cmets 中复制粘贴。我正在修复它:)
    【解决方案2】:

    让自己成为UITextFieldDelegate 的代表并实现以下内容:

    - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
            NSUInteger oldLength = [textField.text length];
            NSUInteger replacementLength = [string length];
            NSUInteger rangeLength = range.length;
    
            NSUInteger newLength = oldLength - rangeLength + replacementLength;
    
            BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
    
            //desired length less than or equal to 5
            return newLength <= 5 || returnKey;
        }
    

    【讨论】:

      【解决方案3】:
      - (BOOL) textField: (UITextField *)textField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
      
          NSString *newText = [textField.text stringByReplacingCharactersInRange: range withString: string];
      
          return [self validateText: newText]; // Return YES if newText is acceptable 
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 2012-05-16
        • 2011-08-09
        • 2015-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多