如何在SwiftUI中更新TextField的值?

3

所以,我希望在更新文本框值之后更改光标位置(输入掩码类似于“+7 000 000 00 00”)。

我有一个文本框:

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的值时,光标位置不会改变。
截图: [

你解决了这个问题吗?我现在也遇到了同样的问题。 - Paul D.
我已经修复了它,使得我创建了一个没有空格和符号的掩码。但问题是:文本字段不会重新计算字符数。(我并不是说视图TextField应该重新计算)。 - Nikita Romanovich
1个回答

0
有点晚回复了。当我看到你的“ObservableObject”,即“LoginChecker”时,我注意到你没有发布任何内容。
Published项目发生变化时,ObservableObject将向SwiftUI发布事件,而你没有这样的项目。
进行以下更改:
@Published var login = "" {
   // This can stay the same
}

有了这个,你应该能够让它工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接