如何以编程方式在swift ios中自动将光标从一个文本字段移动到另一个文本字段?

前端之家收集整理的这篇文章主要介绍了如何以编程方式在swift ios中自动将光标从一个文本字段移动到另一个文本字段?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
func textFieldDidBeginEditing(textField: UITextField) {
    scrlView.setContentOffset(CGPointMake(0,textField.frame.origin.y-70),animated: true)


    if(textField == firstDigit){

        textField.becomeFirstResponder()
        secondDigit.resignFirstResponder()
    }


    else if(textField == secondDigit){

        textField.becomeFirstResponder()
        thirdDigit.resignFirstResponder()
    }

    else if(textField == thirdDigit){
        //textField.becomeFirstResponder()
        fourthDigit.becomeFirstResponder()
    }

我使用四个文本字段进行OTP输入,其中一次只能输入一个数字.输入数字后,我需要将光标自动移动到下一个文本字段.

设置textField委托并添加目标:
override func viewDidLoad() {
        super.viewDidLoad()

        first.delegate = self
        second.delegate = self
        third.delegate = self
        fourth.delegate = self


        first.addTarget(self,action: "textFieldDidChange:",forControlEvents: UIControlEvents.EditingChanged)
        second.addTarget(self,forControlEvents: UIControlEvents.EditingChanged)
        third.addTarget(self,forControlEvents: UIControlEvents.EditingChanged)
        fourth.addTarget(self,forControlEvents: UIControlEvents.EditingChanged)
    }

现在,当文本更改时,更改textField

func textFieldDidChange(textField: UITextField){

    let text = textField.text

    if text?.utf16.count >= 1{
        switch textField{
        case first:
            second.becomeFirstResponder()
        case second:
            third.becomeFirstResponder()
        case third:
            fourth.becomeFirstResponder()
        case fourth:
            fourth.resignFirstResponder()
        default:
            break
        }
    }else{

    }
}

最后当用户开始编辑清除textField时

extension ViewController: UITextFieldDelegate{
    func textFieldDidBeginEditing(textField: UITextField) {
        textField.text = ""
    }
}

猜你在找的Swift相关文章