(在 swift 2 中编程)
我有一个 UITextField,当用户在其中键入内容时,它应该在键入时自动转换为小写字母(因此在表单验证之后不会)。
我已经走到这一步了:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//only convert to lowercase for username field
if textField == textFieldUsername {
//let stringRange = NSRange(location: range.location, length: range.length)
let completedString = (textField.text ?? "" as NSString).stringByReplacingCharactersInRange(range, withString: string)
//convert the while thing to lowercase and assign back to the textfield
textField.text = completedString.lowercaseString
//return false to indicate that the "system" itself should not do anychanges anymore, as we did them
return false
}
//return to the "system" that it can do the changes itself
return true
}
问题是 (1) 当用户按住 UITextField 以 (2) 将光标移动到字符串中途的某个位置并且 (3) 开始键入 (4) 光标跳回到字符串的末尾已经输入的字符串。
是否需要在调用 textField: shouldChangeCharactersInRange 后恢复光标位置?
最佳答案
我已经获取了您的代码并进行了尝试。
我可以在文本更改的任何地方替换光标位置。
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let start = textField.positionFromPosition(textField.beginningOfDocument, offset:range.location)
let cursorOffset = textField.offsetFromPosition(textField.beginningOfDocument, toPosition:start!) + string.characters.count
textField.text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string).lowercaseString
let newCursorPosition = textField.positionFromPosition(textField.beginningOfDocument, offset:cursorOffset)
let newSelectedRange = textField.textRangeFromPosition(newCursorPosition!, toPosition:newCursorPosition!)
textField.selectedTextRange = newSelectedRange
return false
}
关于ios - 在键入和保留光标位置时强制 UITextField 小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35548633/