gpt4 book ai didi

ios - 如何在 Swift 中自动移动到下一个 UITextField

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:21 24 4
gpt4 key购买 nike

我有 2 个带有 NumberPad 键盘类型的文本字段

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

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

我添加了一个条件,通过这段代码在我的文本字段中只接受两个数字:

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
}

最佳答案

使用 UITextFieldDelegate 方法的 shouldChangeCharactersIn 并监听键盘字符串
使用文本字段的标签,如标签 1 和标签 2

作为

class TestingViewController: UIViewController{
@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
firstTextField.delegate = self
secondTextField.delegate = self
firstTextField.tag = 1
secondTextField.tag = 2
firstTextField.keyboardType = .numberPad
secondTextField.keyboardType = .numberPad
}
}

extension TestingViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return textField.shouldChangeCustomOtp(textField: textField, string: string)

}
}

extension UITextField {
func shouldChangeCustomOtp(textField:UITextField, string: String) ->Bool {

//Check if textField has two chacraters
if ((textField.text?.count)! == 1 && string.count > 0) {
let nextTag = textField.tag + 1;
// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil) {
nextResponder = textField.superview?.viewWithTag(1);
}

textField.text = textField.text! + string;
//write here your last textfield tag
if textField.tag == 2 {
//Dissmiss keyboard on last entry
textField.resignFirstResponder()
}
else {
///Appear keyboard
nextResponder?.becomeFirstResponder();
}
return false;
} else if ((textField.text?.count)! == 1 && string.count == 0) {// on deleteing value from Textfield

let previousTag = textField.tag - 1;
// get prev responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil) {
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false
}
return true

}

}

输出:

enter image description here

关于ios - 如何在 Swift 中自动移动到下一个 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48312756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com