Allowing single digit in UITextField in iOS

前端 未结 13 1420
耶瑟儿~
耶瑟儿~ 2020-12-05 03:55

I have a Verification ViewController, I get 4 digit verification code by SMS and I need to enter those code to login, I have created the ViewController

13条回答
  •  温柔的废话
    2020-12-05 04:06

    Provide the tag to the textfield like 1,2,3,4 and directly use it

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    
    
        let next:NSInteger
    
        if string == "" {
    
            next = textField.tag - 1;
    
        }
        else{
    
            next = textField.tag + 1;
    
        }
    
        if (textField.text?.characters.count)! >= 1 {
    
            if textField.tag == 4 {
    
                if string == "" {
    
                    textField.text = ""
    
                    let temptf = self.view.viewWithTag(next) as! UITextField
    
                    temptf.becomeFirstResponder()
    
                    return false
    
                }
                else{
    
                    if (textField.text?.characters.count)! > 1 {
    
                        let stringg = textField.text!
                        textField.text = stringg.replacingOccurrences(of: stringg, with: string)
                    }
                    return false
                }
            }
            else{
                if string == "" {
    
                    textField.text = ""
    
                    if next != 0 {
    
                        let temptf = self.view.viewWithTag(next) as! UITextField
                        temptf.becomeFirstResponder()
    
                    }
    
                    return false
                }
    
                else{
    
                    if (textField.text?.characters.count)! > 1 {
    
    
                        let stringg = textField.text!
                        textField.text = stringg.replacingOccurrences(of: stringg, with: string)
    
                    }
    
                        let temptf = self.view.viewWithTag(next) as! UITextField
    
                        temptf.becomeFirstResponder()
    
                }
            }
        }
    
        return true
    
    }
    

提交回复
热议问题