If your goal is to have all three text fields follow the same rule, set the delegate for all three. The shouldChangeCharactersIn only needs to check the “current” text field into which the user is currently typing.
A minor observation, but I also would avoid recreating the CharacterSet of allowed characters repeatedly. You can simply make that a property.
You might have to experiment whether you want to use localizedUppercase or uppercased() or uppercased(with:).
Note, this “uppercase the whole string” logic is a little sloppy. If you were allowing multi-character strings in your input, you really would want to capture where the cursor was and restore it. (Otherwise it could be an annoying UX where if the user is changing the first character of a multi-character string, the cursor would jump to the end.) E.g., a simple rendition might be:
@IBAction func editingChanged(_ textField: UITextField) {
let range = textField.selectedTextRange
textField.text = textField.text?.localizedUppercase
textField.selectedTextRange = range
}
But for your single character input, the simpler example, above, should be sufficient.
发布评论
评论(1)
如果您的目标是让所有三个文本字段遵循相同的规则,请为这三个文本字段设置
委托
。shouldChangeCharactersIn
只需检查用户当前正在输入的“当前”文本字段。这是一个小观察,但我也会避免重复重新创建允许字符的
CharacterSet
。您可以简单地将其设为属性。这将其简化为:
如果您希望他们只输入大写字符,我会:
将键盘大写更改为“所有字符”,这样他们更有可能不输入小写字母:
可以选择通过为文本字段添加“编辑已更改”操作来更改大小写至:
您可能需要尝试是否要使用
localizedUppercase
或uppercased()
或uppercased(with:)
。注意,这个“整个字符串大写”的逻辑有点草率。如果您允许在输入中使用多字符字符串,您确实希望捕获光标所在位置并恢复它。 (否则,这可能是一个烦人的用户体验,如果用户更改多字符字符串的第一个字符,光标将跳到末尾。)例如,一个简单的再现可能是:
但是对于您的单个字符输入,上面的更简单的示例应该足够了。
If your goal is to have all three text fields follow the same rule, set the
delegate
for all three. TheshouldChangeCharactersIn
only needs to check the “current” text field into which the user is currently typing.A minor observation, but I also would avoid recreating the
CharacterSet
of allowed characters repeatedly. You can simply make that a property.That reduces it down to something like:
If you want them only entering uppercase characters, I would:
Change the keyboard capitalization to “All Characters”, so they are more likely to not enter lowercase letters:
Optionally change the capitalization by adding an “editing changed” action for your text field to:
You might have to experiment whether you want to use
localizedUppercase
oruppercased()
oruppercased(with:)
.Note, this “uppercase the whole string” logic is a little sloppy. If you were allowing multi-character strings in your input, you really would want to capture where the cursor was and restore it. (Otherwise it could be an annoying UX where if the user is changing the first character of a multi-character string, the cursor would jump to the end.) E.g., a simple rendition might be:
But for your single character input, the simpler example, above, should be sufficient.