ios - 在键入和保留光标位置时强制 UITextField 小写

标签 ios swift2 xcode7

(在 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/

相关文章:

arrays - 快速将协议(protocol)数组转换为任何对象

ios - 上传符号文件时 Firebase iOS 多个错误

iphone - 设置新文本时更改 UITextField 中的光标

ios - 如何在 iOS 锁定屏幕上添加搜索按钮?

ios - swift 2 : @objc protocol and enum array

Swift 2.2 中的 iOS UIView.animatewithDuration?

ios - 如何在后台任务中的 AVQueuePlayer 中的 AVPlayerItems 之间进行延迟?

ios - 如何在点击推送通知时打开特定帖子

ios - 无法在 App Store 上分发 react-native iOS 应用程序

ios - 以编程方式创建带帧的 UIImage 动画