如何在Swift中自动移至下一个UITextField

编程入门 行业动态 更新时间:2024-10-05 03:31:28
本文介绍了如何在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

本文发布于:2023-11-28 04:24:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640947.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:移至   如何在   Swift   UITextField

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!