ios - 如何在 SwiftUI 中更新 TextField 的值?

标签 ios swift swiftui textfield observableobject

所以,我想在更新 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 的值时,光标不会改变位置。

截图:

 [

最佳答案

react 有点晚。当我查看您的“ObservableObject”(作为“LoginChecker”)时,我注意到您没有发布任何内容。

ObservableObject 将在 Published 项发生更改时将事件发布到 SwiftUI,而您没有这些项。

进行以下更改:

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

有了它,您应该能够完成这项工作。

关于ios - 如何在 SwiftUI 中更新 TextField 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61383666/

相关文章:

ios - Objective-c 方法队列

swift - 从 Nib 制作 UITableViewCell

arrays - 如何初始化信息数组并追加

ios - 如何将 webview 首选项添加到 swiftui webview

ios - 核心数据上下文不保存

ios - 在 UITableViewCell 中使用 UIPanGestureRecognizer 的问题

ios - 使用 cocoapods 时,更改 PRODUCT_NAME 的最佳方法是什么?

swift - 如何比较忽略关联值的枚举?

swiftui - 如何将 Color 绑定(bind)到 .fill()?

SwiftUI:@Environment(\.presentationMode) 的关闭在 iOS14 中不起作用