我试图通过使用正则表达式删除某些字符来验证文本字段中的用户输入。不幸的是,我遇到了 didSet 方法的问题text
var 递归调用自身。
import SwiftUI
import Combine
class TextValidator: ObservableObject {
@Published var text = "" {
didSet {
print("didSet")
text = text.replacingOccurrences(
of: "\\W", with: "", options: .regularExpression
) // `\W` is an escape sequence that matches non-word characters.
}
}
}
struct ContentView: View {
@ObservedObject var textValidator = TextValidator()
var body: some View {
TextField("Type Here", text: $textValidator.text)
.padding(.horizontal, 20.0)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
On the 快速文档 https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID617(请参阅 AudioChannel 结构),Apple 提供了一个示例,其中在其自己的 didSet 方法中重新分配属性,并明确指出这不会导致再次调用 didSet 方法。我在操场上做了一些测试并证实了这种行为。然而,当我使用时,事情似乎有所不同ObservableObject
and a Published
多变的。
如何防止 didSet 方法递归调用自身?
我尝试了这里的例子post https://stackoverflow.com/questions/56476007/swiftui-textfield-max-length,但没有一个起作用。从那时起,苹果可能已经改变了一些事情,所以这篇文章不是那篇文章的重复。
另外,将文本设置回oldValue
内didSet
遇到无效字符时的方法意味着如果用户粘贴文本,则整个文本将被删除,而不是仅删除无效字符。所以这个选项行不通。
从 SwiftUI 2 开始,您可以使用以下命令检查输入onChange方法并在那里进行任何验证或更改:
TextField("", value: $text)
.onChange(of: text) { [text] newValue in
// do any validation or alteration here.
// 'text' is the old value, 'newValue' is the new one.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)