gpt4 book ai didi

SwiftUI 验证文本字段中的输入

转载 作者:行者123 更新时间:2023-12-03 09:29:22 24 4
gpt4 key购买 nike

我试图通过使用正则表达式删除某些字符来验证 TextField 中的用户输入。不幸的是,我遇到了 text 的 didSet 方法的问题。 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())

}
}

关于 swift docs (请参阅 AudioChannel 结构),Apple 提供了一个示例,其中在其自己的 didSet 方法中重新分配了一个属性,并明确指出这不会导致再次调用 didSet 方法。我在操场上做了一些测试并确认了这种行为。但是,当我使用 ObservableObject 时,事情似乎有所不同。和一个 Published多变的。

如何防止 didSet 方法递归调用自身?

我尝试了这个 post 中的例子,但他们都没有工作。从那以后,Apple 可能已经改变了一些事情,所以这篇文章不是那篇文章的重复。

另外,将文本设置回 oldValuedidSet遇到无效字符的方法意味着如果用户粘贴文本,则整个文本将被删除,而不是仅删除无效字符。所以这个选项不起作用。

最佳答案

尝试在 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)
}
}
}

关于SwiftUI 验证文本字段中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61073146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com