3

So, I want change cursor position after update TextField's value (input mask like "+7 000 000 00 00").

I have TextField:

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

and Class for checking:

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
    }
}

When I update value of TextField, cursor don't change position.

Screenshot:

 [

George
  • 25,988
  • 10
  • 79
  • 133
  • Did you ever figure this out? I'm experiencing the same issue now. – Paul D. Jul 28 '20 at 22:40
  • I fixed it so that I made a mask without spaces and symbols. But the problem is this: the text field does not recount the number of characters. (I am not saying that the view TextField should recalculate). – Nikita Romanovich Jul 30 '20 at 08:06

1 Answers1

0

A bit of a late response. When I look at your 'ObservableObject', being the 'LoginChecker' I notice that you have not published anything.

An ObservableObject will publish events to SwiftUI when changes are happening to Published items, of which you have none.

Make the following change:

@Published var login = "" {
   // This can stay the same
}

With that in place you should be able to make this work.

Fred Appelman
  • 716
  • 5
  • 13