如何实现用于短信验证码的 UITextField 布局/设计?

rgo*_*alv 5 iphone uitextfield ios swift sms-verification

我正在尝试为 SMS 验证代码实现以下功能。我将如何实现它?在查看了 Github 中的一堆库之后,没有一个与这个在行业中广泛使用的设计相似。

我尝试用六个文本字段来实现它,但发现了许多问题,因为做了很多工作,除了第一个文本字段之外的所有初始输入都阻塞了,延迟移动firstResponder等等,是什么让我想知道拥有 6 个文本字段是否真的是最好的方法。

四舍五入的边界是小菜一碟。困难的部分是功能(即光标平滑移动,来回移动,输入错误时将它们全部变为红色等)

你们有什么感想?我怎样才能实现这样的行为/功能?

在此处输入图片说明

小智 7

试试下面的代码。(目前它包含 4 UITextField,根据您的要求更改它。)

extension ConfirmationCodeViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if !(string == "") {
            textField.text = string
            if textField == txtFirst {
                txtSecond.becomeFirstResponder()
            }
            else if textField == txtSecond {
                txtThird.becomeFirstResponder()
            }
            else if textField == txtThird {
                txtForth.becomeFirstResponder()
            }
            else {
                textField.resignFirstResponder()
            }
            return false
        }
        return true
    }

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if (textField.text?.count ?? 0) > 0 {

        }
        return true
    }
}
Run Code Online (Sandbox Code Playgroud)