How to move cursor from one text field to another automatically in swift ios programmatically?

后端 未结 13 2123
抹茶落季
抹茶落季 2020-12-05 08:11
    func textFieldDidBeginEditing(textField: UITextField) {
    scrlView.setContentOffset(CGPointMake(0, textField.frame.origin.y-70), animated: true)


    if(textF         


        
13条回答
  •  遥遥无期
    2020-12-05 09:00

    update Solution For Swift 5

    In This solution, You will go to next Field. And When You Press Erase will come at previous text field.

    Step 1: Set Selector for Text Field

    override func viewDidLoad() {
            super.viewDidLoad()
    
             otpTextField1.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
        otpTextField2.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
        otpTextField3.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
        otpTextField4.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
            
        }
    

    Step 2: Now We will handle move next text Field and Erase text Field.

    @objc func textFieldDidChange(textField: UITextField){
            let text = textField.text
            if  text?.count == 1 {
                switch textField{
                case otpTextField1:
                    otpTextField2.becomeFirstResponder()
                case otpTextField2:
                    otpTextField3.becomeFirstResponder()
                case otpTextField3:
                    otpTextField4.becomeFirstResponder()
                case otpTextField4:
                    otpTextField4.resignFirstResponder()
                default:
                    break
                }
            }
            if  text?.count == 0 {
                switch textField{
                case otpTextField1:
                    otpTextField1.becomeFirstResponder()
                case otpTextField2:
                    otpTextField1.becomeFirstResponder()
                case otpTextField3:
                    otpTextField2.becomeFirstResponder()
                case otpTextField4:
                    otpTextField3.becomeFirstResponder()
                default:
                    break
                }
            }
            else{
    
            }
        }
    

    Important Note: Don't Forget To set Delegate.

提交回复
热议问题