如何在Swift中自动移至下一个UITextField [英] How to move to the next UITextField automatically in Swift

查看:126
本文介绍了如何在Swift中自动移至下一个UITextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个具有NumberPad键盘类型的textFields

I have 2 textFields with NumberPad keyboard type

@IBOutlet weak var ourTextField: UITextField!
@IBOutlet weak var forThemTextField: UITextField!

并且我想在ourTextField中输入两个数字后自动移动到另一个文本字段(从ourTextField到forThemTextField),然后在转到另一个文本字段(forThemTextField)并输入两个数字后我希望键盘自动隐藏

and I want to automatically move to the other textfield (from ourTextField to forThemTextField) after entering two numbers inside the ourTextField then after going to the other textfield (forThemTextField) and entering 2 numbers I want the keyboard hide automatically

通过此代码,我添加了一个条件,只能在我的textFields中接受两个数字:

I have added a condition to only accept two numbers in my textFields by this code :

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let lengthsDictionary = [ourTextField : 2, forThemTextField: 2]
    guard let length = lengthsDictionary[textField] else {
        return true
    }
    let currentCharacterCount = textField.text?.count ?? 0
    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.count - range.length

    return newLength <= length
}

推荐答案

In viewDidLoad :- 

ourTextField?.addTarget(self, action: #selector(CalculatorViewController.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)

forThemTextField?.addTarget(self, action: #selector(CalculatorViewController.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)


//create function

func textFieldDidChange(_ textField: UITextField) {
        if textField == ourTextField {
            if (textField.text.count)! >= 2 {
                forThemTextField?.becomeFirstResponder()
            }
        }
        else if textField == forThemTextField {
            if (textField.text?.count)! >= 2 {
                forThemTextField.resignFirstResponder()
            }
        }
    }

这篇关于如何在Swift中自动移至下一个UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆