在文本字段中检测剪切操作-Swift

时间:2019-01-03 12:46:59

标签: ios swift uitextfielddelegate

我已经实现了shouldChangeCharactersIn文本字段委托方法。我已经格式化了文本字段中的值,以便文本字段字符串成为逗号分隔的货币类型值。为此,我明确地处理了游标以支持条件,例如一次插入两个逗号。使用的代码是:

let textBeforeEditing = textField.text!
    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: string == "" ? selectedRange.end : selectedRange.start)
    }
    let allowedCharacterSet = NSCharacterSet(charactersIn: "0123456789.").inverted
    let filtered = string.components(separatedBy: allowedCharacterSet)
    let component = filtered.joined(separator: "")
    let isNumeric = string.replacingOccurrences(of: ",", with: "") == component
    var textFieldString : String = ""
    var numberWithoutCommas : String = ""
    guard isNumeric else {
        return false
    }
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    textFieldString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    numberWithoutCommas = textFieldString.replacingOccurrences(of: ",", with: "")
    let formattedNumberWithoutCommas = formatter.number(from: numberWithoutCommas)
    guard let formattedNumber = formattedNumberWithoutCommas, var formattedString = formatter.string(from: formattedNumber) else {
        textField.text = nil
        return false
    }
    if string == "." && range.location == textField.text?.count {
        formattedString = formattedString.appending(".")
    }
    var filteredRegex = [NSTextCheckingResult]()
    filteredRegex = Constant.Regex.decimalRegex.matches(in: formattedString, options: [], range: NSMakeRange(0, formattedString.count))
    guard filteredRegex.count == 1 else {
        return false
    }
    textField.text = formattedString
    currentPosition = getCursorPositionForTextField(string: string, cursorPosition: currentPosition, formattedString: formattedString, textBeforeEditing: textBeforeEditing)
    handleTextFieldCursor(cursorPosition: currentPosition, textField: textField)
    return false

因此,当我输入1234567890时,其格式将变为1,234,567,890

这里的问题是,当我从文本字段剪切任何字符时,无法将其粘贴到其他任何地方。我无法检测到未粘贴的原因。请有人帮我。

有没有办法检测相同的切割操作?看起来上面的代码覆盖了剪切操作。

0 个答案:

没有答案