ios - 如果我们使用多个文本字段,如何自动获取 OTP
问题描述
我知道如果我们想自动获取 OTP(如果我们使用单个文本字段),我们需要使用
otpTextField.textContentType = .oneTimeCode
但是,如果我们使用多个文本字段(根据下图)
我们应该如何做到这一点?
解决方案
-> 从 iOS 12 开始,Apple 将允许支持读取您将在 iPhone 设备中获得的一次性代码。您可以将文本拆分为四个字段并自动填充并手动输入 otp 并逐个删除并移动每个文本字段。
1) self.textone 最大长度 4 和其他文本字段最大长度 1
2) 添加 UITextFieldDelegate
if #available(iOS 12.0, *) {
txtOne.textContentType = .oneTimeCode
}
self.txtOne.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.txtOne.becomeFirstResponder()
@objc func textFieldDidChange(_ textField: UITextField) {
if #available(iOS 12.0, *) {
if textField.textContentType == UITextContentType.oneTimeCode{
//here split the text to your four text fields
if let otpCode = textField.text, otpCode.count > 3{
txtOne.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 0)])
txtTwo.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 1)])
txtThree.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 2)])
txtFour.text = String(otpCode[otpCode.index(otpCode.startIndex, offsetBy: 3)])
}
}
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (string.count == 1){
if textField == txtOne {
txtTwo?.becomeFirstResponder()
}
if textField == txtTwo {
txtThree?.becomeFirstResponder()
}
if textField == txtThree {
txtFour?.becomeFirstResponder()
}
if textField == txtFour {
txtFour?.resignFirstResponder()
textField.text? = string
//APICall Verify OTP
//Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.VerifyOTPAPI), userInfo: nil, repeats: false)
}
textField.text? = string
return false
}else{
if textField == txtOne {
txtOne?.becomeFirstResponder()
}
if textField == txtTwo {
txtOne?.becomeFirstResponder()
}
if textField == txtThree {
txtTwo?.becomeFirstResponder()
}
if textField == txtFour {
txtThree?.becomeFirstResponder()
}
textField.text? = string
return false
}
}
推荐阅读
- serenity-bdd - Serenity BDD 剧本验证网页上的多个文本元素
- html - 当跨所有浏览器加载 HTML 文件时,iframe 显示“内容可能已被移动、删除或编辑”
- java - 将实体移动到另一个拥有的 OneToMany 集合中
- npm - 将 Azure Devops $(Build.BuildNumber) 传递给 npm 任务
- amazon-web-services - AppSync Dynamodb 解析器
- php - Web 文件夹可在本地主机上访问,但在 Web 服务器上找不到
- mysql - 插入...在重复的密钥更新上...如果
- go - 如何在 Go 中从 Azure AD 获取 OAuth2.0 令牌?
- javascript - 尝试在卡内使用 :HOVER 进行缩放时,IMG 会不断调整大小
- css - Flexbox justify-content:center vs overflow:auto