Input-mask-ios: Máscara incorreta anexada após a edição

Criado em 25 jul. 2018  ·  11Comentários  ·  Fonte: RedMadRobot/input-mask-ios

Tenho o seguinte conjunto de máscaras:
self.login.affineFormats = [ "{+7} ([000]) [000] [00] [00]", "{8} ([000]) [000]-[00]-[00]" ]

Quando eu digito um número de telefone com máscara +7 e, em seguida, edito o valor dentro de ([000]), a máscara muda para 8 em vez de +7 e, em seguida, 7 é colocado dentro ([000])

enhancement

Comentários muito úteis

Sim resolveu, obrigado!

Todos 11 comentários

Talvez haja uma maneira de "bloquear" a máscara no textField depois de inicializada com qualquer uma das máscaras?

Olá @MrJox , obrigado pelo seu relato.
Você poderia fornecer os estados exatos do texto dentro do seu campo de texto quando esse erro ocorrer?

Poderei rastreá-lo ainda hoje e ajudá-lo com a solução.

Não tenho certeza do que você quer dizer com estados, mas aqui está o que acontece:

Eu tenho um número de telefone lido do cache e inserido no textField (é um textField JVFloat personalizado).
O número de telefone é +7 (926) 000-00-00 e, em seguida, defino o ponteiro após '2' e excluo esse número. Como resultado, meu conteúdo textView é convertido em 8 (796) 000-00-00.

Então, por algum motivo, ele exclui + e trata 7 não como máscara, mas como uma parte real do número de telefone e o coloca entre colchetes e adiciona a máscara 8.

Sim, sua descrição funciona para mim, obrigado!
Fique ligado.

@MrJox enquanto estou trabalhando em algumas melhorias e correções exigidas pela nossa última atualização de biblioteca, reuni uma solução rápida para o seu problema.

Efetivamente, é uma modificação PolyMaskTextFieldDelegate com um método de cálculo de afinidade personalizado. Em vez de uma afinidade geral de texto com a máscara, esse método compara o comprimento da interseção de prefixos, a contagem de caracteres.

Esse código ou sua versão modificada pode eventualmente encontrar o caminho para as fontes da biblioteca.

import Foundation
import UIKit

import InputMask

<strong i="10">@IBDesignable</strong>
class PrefixAffinityMaskedTextFieldDelegate: MaskedTextFieldDelegate {
    public var affineFormats: [String]

    public init(primaryFormat: String, affineFormats: [String]) {
        self.affineFormats = affineFormats
        super.init(format: primaryFormat)
    }

    public override init(format: String) {
        self.affineFormats = []
        super.init(format: format)
    }

    override open func put(text: String, into field: UITextField) {
        let mask: Mask = pickMask(
            forText: text,
            caretPosition: text.endIndex,
            autocomplete: autocomplete
        )

        let result: Mask.Result = mask.apply(
            toText: CaretString(
                string: text,
                caretPosition: text.endIndex
            ),
            autocomplete: autocomplete
        )

        field.text = result.formattedText.string
        field.caretPosition = result.formattedText.string.distance(
            from: result.formattedText.string.startIndex,
            to: result.formattedText.caretPosition
        )

        listener?.textField?(field, didFillMandatoryCharacters: result.complete, didExtractValue: result.extractedValue)
    }

    override open func deleteText(inRange range: NSRange, inTextInput field: UITextInput) -> Mask.Result {
        let text: String = replaceCharacters(
            inText: field.allText,
            range: range,
            withCharacters: ""
        )

        let mask: Mask = pickMask(
            forText: text,
            caretPosition: text.index(text.startIndex, offsetBy: range.location),
            autocomplete: false
        )

        let result: Mask.Result = mask.apply(
            toText: CaretString(
                string: text,
                caretPosition: text.index(text.startIndex, offsetBy: range.location)
            ),
            autocomplete: false
        )

        field.allText = result.formattedText.string
        field.caretPosition = range.location

        return result
    }

    override open func modifyText(
        inRange range: NSRange,
        inTextInput field: UITextInput,
        withText text: String
    ) -> Mask.Result {
        let updatedText: String = replaceCharacters(
            inText: field.allText,
            range: range,
            withCharacters: text
        )

        let mask: Mask = pickMask(
            forText: updatedText,
            caretPosition: updatedText.index(updatedText.startIndex, offsetBy: field.caretPosition + text.count),
            autocomplete: autocomplete
        )

        let result: Mask.Result = mask.apply(
            toText: CaretString(
                string: updatedText,
                caretPosition: updatedText.index(updatedText.startIndex, offsetBy: field.caretPosition + text.count)
            ),
            autocomplete: autocomplete
        )

        field.allText = result.formattedText.string
        field.caretPosition = result.formattedText.string.distance(
            from: result.formattedText.string.startIndex,
            to: result.formattedText.caretPosition
        )

        return result
    }

    func pickMask(forText text: String, caretPosition: String.Index, autocomplete: Bool) -> Mask {
        let primaryAffinity: Int = calculateAffinity(
            ofMask: mask,
            forText: text,
            caretPosition: caretPosition,
            autocomplete: autocomplete
        )

        var masks: [(Mask, Int)] = affineFormats.map { (affineFormat: String) -> (Mask, Int) in
            let mask:     Mask = try! Mask.getOrCreate(withFormat: affineFormat, customNotations: customNotations)
            let affinity: Int  = calculateAffinity(
                ofMask: mask,
                forText: text,
                caretPosition: caretPosition,
                autocomplete: autocomplete
            )

            return (mask, affinity)
        }

        masks.sort { (left: (Mask, Int), right: (Mask, Int)) -> Bool in
            return left.1 > right.1
        }

        var insertIndex: Int = -1

        for (index, maskAffinity) in masks.enumerated() {
            if primaryAffinity >= maskAffinity.1 {
                insertIndex = index
                break
            }
        }

        if (insertIndex >= 0) {
            masks.insert((mask, primaryAffinity), at: insertIndex)
        } else {
            masks.append((mask, primaryAffinity))
        }

        return masks.first!.0
    }

    func calculateAffinity(
        ofMask mask: Mask,
        forText text: String,
        caretPosition: String.Index,
        autocomplete: Bool
    ) -> Int {
        return mask.apply(
            toText: CaretString(
                string: text,
                caretPosition: caretPosition
            ),
            autocomplete: autocomplete
        ).formattedText.string.prefixIntersection(with: text).count
    }

    func replaceCharacters(inText text: String, range: NSRange, withCharacters newText: String) -> String {
        if 0 < range.length {
            let result = NSMutableString(string: text)
            result.replaceCharacters(in: range, with: newText)
            return result as String
        } else {
            let result = NSMutableString(string: text)
            result.insert(newText, at: range.location)
            return result as String
        }
    }

}


extension String {

    func prefixIntersection(with string: String) -> Substring {
        let lhsStartIndex = startIndex
        var lhsEndIndex = startIndex
        let rhsStartIndex = string.startIndex
        var rhsEndIndex = string.startIndex

        while (self[lhsStartIndex...lhsEndIndex] == string[rhsStartIndex...rhsEndIndex]) {
            lhsEndIndex = lhsEndIndex != endIndex ? index(after: lhsEndIndex) : endIndex
            rhsEndIndex = rhsEndIndex != string.endIndex ? string.index(after: rhsEndIndex) : endIndex

            if (lhsEndIndex == endIndex || rhsEndIndex == string.endIndex) {
                return self[lhsStartIndex..<lhsEndIndex]
            }
        }

        return self[lhsStartIndex..<lhsEndIndex]
    }

}


extension UITextInput {
    var allText: String {
        get {
            guard let all: UITextRange = allTextRange
                else { return "" }
            return self.text(in: all) ?? ""
        }

        set(newText) {
            guard let all: UITextRange = allTextRange
                else { return }
            self.replace(all, withText: newText)
        }
    }

    var caretPosition: Int {
        get {
            if let responder = self as? UIResponder {
                // Workaround for non-optional `beginningOfDocument`, which could actually be nil if field doesn't have focus
                guard responder.isFirstResponder
                    else { return allText.count }
            }

            if let range: UITextRange = selectedTextRange {
                let selectedTextLocation: UITextPosition = range.start
                return offset(from: beginningOfDocument, to: selectedTextLocation)
            } else {
                return 0
            }
        }

        set(newPosition) {
            if let responder = self as? UIResponder {
                // Workaround for non-optional `beginningOfDocument`, which could actually be nil if field doesn't have focus
                guard responder.isFirstResponder
                    else { return }
            }

            if newPosition > allText.count {
                return
            }

            let from: UITextPosition = position(from: beginningOfDocument, offset: newPosition)!
            let to:   UITextPosition = position(from: from, offset: 0)!
            selectedTextRange = textRange(from: from, to: to)
        }
    }

    var allTextRange: UITextRange? {
        return self.textRange(from: self.beginningOfDocument, to: self.endOfDocument)
    }
}

Hm, então agora eu faço isso:
<strong i="6">@IBOutlet</strong> var loginListener: PrefixAffinityMaskedTextFieldDelegate!

Mas ainda não vai funcionar. O que eu notei, se você excluir dígitos entre colchetes com a tecla Del, o dígito será excluído e agora é um dígito a menos entre colchetes, no entanto, quando eu excluo com o botão Backspace, ele coloca / move o dígito da esquerda ou o dígito da direita para a quantidade de dígitos entre colchetes permanece inalterada.

O que eu quero dizer:
original: +7 (916) 000-00-00
com tecla del: +7 (96) 000-00-00
com tecla de retrocesso: 8 (796) 000-00-00

Correção:
Agora parece funcionar, no entanto, quando tento excluir a string no textField, tenho apenas o caractere '+' restante e meu aplicativo trava quando tento excluí-lo com

Thread 1: Erro fatal: não é possível incrementar além de endIndex

@MrJox Não tenho certeza se entendi corretamente.
Observe que não há chave Del no iOS, apenas Backspace . Não deixe a emulação de teclado virtual enganar você.

Em relação ao seu último erro, você pode considerar o seguinte patch para o caso extremo:

extension String {

    func prefixIntersection(with string: String) -> Substring {
        guard !self.isEmpty && !string.isEmpty
        else { return "" }

        let lhsStartIndex = startIndex
        var lhsEndIndex = startIndex
        let rhsStartIndex = string.startIndex
        var rhsEndIndex = string.startIndex

        while (self[lhsStartIndex...lhsEndIndex] == string[rhsStartIndex...rhsEndIndex]) {
            lhsEndIndex = lhsEndIndex != endIndex ? index(after: lhsEndIndex) : endIndex
            rhsEndIndex = rhsEndIndex != string.endIndex ? string.index(after: rhsEndIndex) : endIndex

            if (lhsEndIndex == endIndex || rhsEndIndex == string.endIndex) {
                return self[lhsStartIndex..<lhsEndIndex]
            }
        }

        return self[lhsStartIndex..<lhsEndIndex]
    }

}

Sim resolveu, obrigado!

@MrJox Vou fechar este problema com a próxima atualização da biblioteca.
Estou pensando em adicionar isso às fontes da biblioteca como uma estratégia alternativa.

@MrJox versão otimizada e simplificada:

extension String {

    func prefixIntersection(with string: String) -> Substring {
        var lhsIndex = startIndex
        var rhsIndex = string.startIndex

        while lhsIndex != endIndex && rhsIndex != string.endIndex {
            if self[...lhsIndex] == string[...rhsIndex] {
                lhsIndex = index(after: lhsIndex)
                rhsIndex = string.index(after: rhsIndex)
            } else {
                return self[..<lhsIndex]
            }
        }

        return self[..<lhsIndex]
    }

}

4.0.0 contém isso como um recurso.

Esta página foi útil?
0 / 5 - 0 avaliações

Questões relacionadas

LinusGeffarth picture LinusGeffarth  ·  4Comentários

beltik picture beltik  ·  6Comentários

osterlind picture osterlind  ·  3Comentários

SteynMarnus picture SteynMarnus  ·  11Comentários

caioremedio picture caioremedio  ·  6Comentários