Как я могу обновить значение TextField в SwiftUI? - PullRequest
1 голос
/ 23 апреля 2020

Итак, я хочу изменить позицию курсора после обновления значения TextField (маска ввода типа "+7 000 000 00 00").

У меня есть TextField:

TextField("+7 000 000 00 00", text: $loginChecker.login)
                        .textContentType(.telephoneNumber)
                        .keyboardType(.numberPad)
                        .disableAutocorrection(true)
                        .textFieldStyle(BasicTextField())

и класс для проверка:

class LoginChecker: ObservableObject {
    var full = false
    var login = "" {
        willSet {
            if newValue.count > 16 {
                self.full = true
            } else {
                self.full = false
            }
        }
        didSet {
            if self.full {
                self.login = oldValue
            } else {
                self.login = self.phoneFormatter()
            }
            self.objectWillChange.send()
        }
    }

    func phoneFormatter () -> String {
        let numbers = onlyNumbers(self.login)
        var newValue = numbers.first == "7" ? String(numbers.dropFirst()) : numbers

        if numbers.count > 0 {
            newValue.insert("+", at: newValue.startIndex)
            newValue.insert("7", at: newValue.index(newValue.startIndex, offsetBy: 1))
            newValue.insert(" ", at: newValue.index(newValue.startIndex, offsetBy: 2))
            if numbers.count > 4 {
                newValue.insert(" ", at: newValue.index(newValue.startIndex, offsetBy: 6))
                if numbers.count > 7 {
                    newValue.insert(" ", at: newValue.index(newValue.startIndex, offsetBy: 10))
                    if numbers.count > 9 {
                        newValue.insert(" ", at: newValue.index(newValue.startIndex, offsetBy: 13))
                    }
                }
            }
        }

        return newValue
    }
}

Когда я обновляю значение TextField, курсор не меняет положение.

Снимок экрана:

[

...