光标移动到编辑格式化的十进制文本字段时结束 - Swift [英] Cursor shifts to end on edit of formatted decimal textfield - Swift

查看:18
本文介绍了光标移动到编辑格式化的十进制文本字段时结束 - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在格式化一个 UITextField 以便它在输入时变成逗号分隔(十进制样式).

I am formatting a UITextField such that it becomes comma separated (Decimal style) while typing.

所以 12345678 变成了 12,345,678

现在,当我编辑 UITextField 时,说我想删除 5,那时我在 5 之后点击并删除它,但是光标立即移动到文本的末尾,即 8 之后.

Now when I edit the UITextField, say I want to remove 5, at that time I tap after 5 and delete it but the cursor shifts to the end of the text immediately, that's after 8.

这是我在打字时用来格式化小数的代码:

Here's my code which I have used to format the decimal while typing:

func checkTextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if ((string == "0" || string == "") && (textField.text! as NSString).range(of: ".").location < range.location) {
        return true
    }
    let allowedCharacterSet = NSCharacterSet(charactersIn: "0123456789.").inverted
    let filtered = string.components(separatedBy: allowedCharacterSet)
    let component = filtered.joined(separator: "")
    let isNumeric = string == component
    if isNumeric {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
        let number = formatter.number(from: numberWithOutCommas)
        if number != nil {
            var formattedString = formatter.string(from: number!)
            if string == "." && range.location == textField.text?.count {
                formattedString = formattedString?.appending(".")
            }
            textField.text = formattedString
        } else {
            textField.text = nil
        }
    }
    return false
}

它是这样调用的:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let textFieldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let checkForCurrency = checkTextField(textField, shouldChangeCharactersIn: range, replacementString: string)
    return checkForCurrency
}

我尝试了以下但徒劳无功:

I have tried the following but in vain :

解决方案 1

解决方案 2

光标移动的原因可能是什么?它应该类似于这个链接任何帮助将不胜感激!

What could the reason for cursor shift be? It should be something like in this link Any help would be appreciated!

推荐答案

更新您的自定义函数:

update your custom function with :

func checkTextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        let textFieldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if ((string == "0" || string == "") && (textField.text! as NSString).range(of: ".").location < range.location) {
            return true
        }

        var currentPosition = 0
        if let selectedRange = textField.selectedTextRange {
            currentPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
        }

        let allowedCharacterSet = NSCharacterSet(charactersIn: "0123456789.").inverted
        let filtered = string.components(separatedBy: allowedCharacterSet)
        let component = filtered.joined(separator: "")
        let isNumeric = string == component
        if isNumeric {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
            let number = formatter.number(from: numberWithOutCommas)

            if number != nil {
                var formattedString = formatter.string(from: number!)
                if string == "." && range.location == textField.text?.count {
                    formattedString = formattedString?.appending(".")
                }
                textField.text = formattedString

                if(textFieldText.count < formattedString?.count ?? 0){
                    currentPosition = currentPosition + 1
                }
            }else{
                textField.text = nil
            }
        }

        if(string == ""){
            currentPosition = currentPosition - 1
        }else{
           currentPosition = currentPosition + 1
        }

        if let newPosition = textField.position(from: textField.beginningOfDocument, offset: currentPosition) {
            textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
        }
        return false
    }

这篇关于光标移动到编辑格式化的十进制文本字段时结束 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆