简体   繁体   English

如何更新 SwiftUI 中 TextField 的值?

[英]How can I update value of TextField in SwiftUI?

So, I want change cursor position after update TextField's value (input mask like "+7 000 000 00 00").所以,我想在更新 TextField 的值(输入掩码如“+7 000 000 00 00”)后更改 cursor position。

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 用于检查:

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.当我更新 TextField 的值时,cursor 不要更改 position。

Screenshot:截屏:

[

A bit of a late response.回复有点晚。 When I look at your 'ObservableObject', being the 'LoginChecker' I notice that you have not published anything.当我查看您的“ObservableObject”时,作为“LoginChecker”,我注意到您没有发布任何内容。

An ObservableObject will publish events to SwiftUI when changes are happening to Published items, of which you have none.当已Published项目发生更改时, ObservableObject将向SwiftUI发布事件,而您没有。

Make the following change:进行以下更改:

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

With that in place you should be able to make this work.有了这个,你应该能够完成这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM