Allowing single digit in UITextField in iOS

前端 未结 13 1440
耶瑟儿~
耶瑟儿~ 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:00

    Use this code if you don't want to work with tag and it works better then above

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            // On inputing value to textfield
            if ((textField.text?.characters.count)! < 1  && string.characters.count > 0){
                if(textField == txtOne)
                {
                    txtTwo.becomeFirstResponder()
                }
                if(textField == txtTwo)
                {
                    txtThree.becomeFirstResponder()
                }
                if(textField == txtThree)
                {
                    txtFour.becomeFirstResponder()
                }
    
                textField.text = string
                return false
            }
            else if ((textField.text?.characters.count)! >= 1  && string.characters.count == 0){
                // on deleting value from Textfield
                if(textField == txtTwo)
                {
                    txtOne.becomeFirstResponder()
                }
                if(textField == txtThree)
                {
                    txtTwo.becomeFirstResponder()
                }
                if(textField == txtFour)
                {
                    txtThree.becomeFirstResponder()
                }
                textField.text = ""
                return false
            }
            else if ((textField.text?.characters.count)! >= 1  )
            {
                textField.text = string
                return false
            }
            return true
        }
    

提交回复
热议问题