gpt4 book ai didi

ios - 刚好输入一个数字后移至下一个 UITextField

转载 作者:行者123 更新时间:2023-11-28 10:09:36 25 4
gpt4 key购买 nike

我想为客户 ID 制作一个登录屏幕,它接受数字键盘的数字输入,并在用户输入一个数字后移动到下一个 UITextField

我有五个 UITextField,第一个 UITextField 应该成为带有数字键盘的第一响应者,并且应该在不按回车键的情况下通过这些字段。四个 UITextField 是,

@IBOutlet weak var customerIdOne: UITextField!
@IBOutlet weak var customerIdTwo: UITextField!
@IBOutlet weak var customerIDThree: UITextField!
@IBOutlet weak var customerIdFive: UITextField!
@IBOutlet weak var customerIdFour: UITextField!

在按下登录按钮时,UITextField 中的所有值都应该连接起来。

@IBAction func loginButton(_ sender: Any) {
custID = "\(customerIdOne.text!)\(customerIdTwo.text!)\(customerIDThree.text!)\(customerIdFour.text!)\(customerIdFive.text!)"
print(custID)
}

我是初学者,我想知道是否有有效的方法来实现这一点。

目前,我使用带有 textFieldShouldReturn 委托(delegate)方法的标签

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.tag == 1
{
customerIdOne.resignFirstResponder()
customerIdTwo.becomeFirstResponder()
}

if textField.tag == 2
{
customerIdTwo.resignFirstResponder()
customerIDThree.becomeFirstResponder()
}
if textField.tag == 3
{
customerIDThree.resignFirstResponder()
customerIdFour.becomeFirstResponder()
}
if textField.tag == 4
{
customerIdFour.resignFirstResponder()
customerIdFive.becomeFirstResponder()
}
if textField.tag == 5
{
customerIdFive.resignFirstResponder()
}
return false
}

最佳答案

第一步

创建 IBOutletCollections 并为每个文本字段设置 标签 以识别用户点击了哪个文本字段。

@IBOutlet var customerIdButtons: [UITextField]!

第二步

为文本域创建公共(public)扩展

extension yourViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = ((textField.text)! as NSString).replacingCharacters(in: range, with: string)
if newString.count == 1 {
textFieldShouldReturnSingle(textField, newString : newString)
return false
}
return true
}
func textFieldShouldReturnSingle(_ textField: UITextField, newString : String)
{


let nextTag: Int = textField.tag + 1
textField.text = newString
let nextResponder: UIResponder? = textField.superview?.viewWithTag(nextTag)
if let nextR = nextResponder
{
// Found next responder, so set it.
nextR.becomeFirstResponder()
}
else
{
// Not found, so remove keyboard.
textField.resignFirstResponder()
// call your method
}
}

}

最后获取所有客户ID,然后使用

@IBAction func loginButton(_ sender: Any) {
var texts: [String] = []
customerIdButtons.forEach { texts.append($0.text!)}
custID = texts.reduce("", +)
print(custID)
}

关于ios - 刚好输入一个数字后移至下一个 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49691812/

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