我试图通过使用正则表达式删除某些字符来验证TextField中的用户输入。不幸的是,我遇到了text
var递归调用自身的didSet方法的问题。
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())
}
}
在迅速的文档(请参阅AudioChannel结构)上,Apple提供了一个示例,在该示例中,在其自己的didSet方法中重新分配了一个属性,并明确指出这不会导致didSet方法被再次调用。我在操场上做了一些测试,并确认了这种行为。但是,当我使用ObservableObject
和Published
变量时,情况似乎有所不同。
如何防止didSet方法递归调用自身?
我试过例子这个岗位,但他们没有工作。从那以后,Apple可能已经改变了一切,因此这篇文章不是该文章的重复。
同样,在遇到无效字符时将文本设置回方法oldValue
内didSet
意味着,如果用户粘贴文本,则将删除整个文本,而不是仅删除无效字符。因此,该选项将不起作用。
尝试通过以下TextField
onRecive
方法验证您想要的内容:
class TextValidator: ObservableObject {
@Published var text = ""
}
struct ContentView: View {
@ObservedObject var textValidator = TextValidator()
var body: some View {
TextField("Type Here", text: $textValidator.text)
.padding(.horizontal, 20.0)
.textFieldStyle(RoundedBorderTextFieldStyle())
.onReceive(Just(textValidator.text)) { newValue in
let value = newValue.replacingOccurrences(
of: "\\W", with: "", options: .regularExpression)
if value != newValue {
self.textValidator.text = value
}
print(newValue)
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句