我有一个包含三个文本字段的SwiftUI屏幕。当您运行代码并点击清除按钮时,您将看到三个完全空白的文本字段。可以预期的是,您会看到占位符文本,但是仅在每个文本字段获得焦点(即用户在字段内轻按)时才会显示。
class UserInput: ObservableObject {
@Published var text1 = "some text"
@Published var text2 = "some more text"
@Published var text3 = "and this is the final input"
func clear() {
self.text1 = ""
self.text2 = ""
self.text3 = ""
}
}
struct ContentView: View {
@ObservedObject var userInput = UserInput()
var body: some View {
Form {
TextField("Type something in text1", text: self.$userInput.text1)
TextField("Type something in text2", text: self.$userInput.text2)
TextField("Type something in text3", text: self.$userInput.text3)
Button("Clear all fields", action: self.userInput.clear)
}
}
}
我是否缺少某些东西,或者是否有针对此行为的解决方法?
答案 0 :(得分:3)
我找到了解决方法。基本上,我发送一个用户永远无法键入的特殊字符,然后捕获该字符并在表单本身中“本地”清除字段。它可以正常工作,并按预期恢复占位符。
随着变通办法的进行,这一步很难看。
class UserInput: ObservableObject {
static let clearCode = String.Element(Unicode.Scalar(7))
@Published var text1 = "some text"
@Published var text2 = "some more text"
@Published var text3 = "and this is the final input"
func clear() {
self.text1 = String(Self.clearCode)
self.text2 = String(Self.clearCode)
self.text3 = String(Self.clearCode)
}
}
struct ContentView: View {
@ObservedObject var userInput = UserInput()
var body: some View {
Form {
TextField("Type something in text1", text: self.$userInput.text1)
.onReceive(self.userInput.text1.publisher) { newValue in
if newValue == UserInput.clearCode {
self.userInput.text1 = ""
}
}
TextField("Type something in text2", text: self.$userInput.text2)
.onReceive(self.userInput.text2.publisher) { newValue in
if newValue == UserInput.clearCode {
self.userInput.text2 = ""
}
}
TextField("Type something in text3", text: self.$userInput.text3)
.onReceive(self.userInput.text3.publisher) { newValue in
if newValue == UserInput.clearCode {
self.userInput.text3 = ""
}
}
Button("Clear all fields", action: self.userInput.clear)
}
}
}
我尝试了以下解决方案,但未提供解决方法,但仍清除了占位符。
class UserInput: ObservableObject {
let clearPublisher = PassthroughSubject<Bool, Never>()
// ...
func clear() {
self.clearPublisher.send(true)
}
}
struct ContentView: View {
// ...
TextField("Type something in text1", text: self.$userInput.text1)
.onReceive(self.userInput.clearPublisher) { _ in
self.userInput.text1 = ""
}
// ...