【发布时间】:2017-06-14 05:45:27
【问题描述】:
我有 4 个 UITextFields 在一个 UIView 中,如下所示:
每个 UITextField 限制为 4 个字符。我想实现UITextFields 之间的自动切换,每个UITextField 的计数字符。
我使用shouldChangeCharactersIn 作为限制字符:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 4
var newString = String()
let currentString: NSString = textField.text! as NSString
newString = currentString.replacingCharacters(in: range, with: string)
return newString.length <= maxLength
}
这是我的开关工具:
func textFieldDidChange(_ textField: UITextField){
let text = textField.text
if text?.utf16.count == 4 {
switch textField {
case firstPartTextField:
secondPartTextField.becomeFirstResponder()
case secondPartTextField:
thirdPartTextField.becomeFirstResponder()
case thirdPartTextField:
fourthPartTextField.becomeFirstResponder()
default:
break
}
}
}
我的问题是在删除文本时切换到以前的UITextField,当UITextField 为空时,我无法检测到退格事件。
【问题讨论】:
-
(1) Not all credit cards are 16-digit long (2) 也许你可以使用existing libraries 而不是自己发明。
-
试试这个答案,这对我有用stackoverflow.com/a/39483754/6245319
-
我个人不喜欢在 4 个单独的文本字段中输入数字 :(
-
例如,使用这 4 个文本字段无法从我的 1Password 粘贴信用卡 :(
标签: ios iphone swift uitextfield uitextfielddelegate