![](/img/trans.png)
[英]How can I programmatically edit TextField's border color in SwiftUI?
[英]How can I update value of TextField in SwiftUI?
所以,我想在更新 TextField 的值(輸入掩碼如“+7 000 000 00 00”)后更改 cursor position。
我有文本字段:
TextField("+7 000 000 00 00", text: $loginChecker.login)
.textContentType(.telephoneNumber)
.keyboardType(.numberPad)
.disableAutocorrection(true)
.textFieldStyle(BasicTextField())
和 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
}
}
當我更新 TextField 的值時,cursor 不要更改 position。
截屏:
回復有點晚。 當我查看您的“ObservableObject”時,作為“LoginChecker”,我注意到您沒有發布任何內容。
當已Published
項目發生更改時, ObservableObject
將向SwiftUI
發布事件,而您沒有。
進行以下更改:
@Published var login = "" {
// This can stay the same
}
有了這個,你應該能夠完成這項工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.