我正在尝试布置一组CustomTextView
,它们可以在SwiftUITextField
或Text
视图之间切换。
考虑这个例子。
import SwiftUI
struct ContentView: View {
@StateObject var doc: Document = Document()
var body: some View {
ForEach(doc.lines, id: .self) { line in
HStack {
ForEach(line, id: .self) { word in
CustomTextView(text: word, document: doc)
.fixedSize()
}
Spacer()
}
}
.frame(width: 300, height: 300)
.background(.cyan)
}
}
struct CustomTextView: View {
@State var text: String
@State var isEditing: Bool = false
@ObservedObject var document: Document
var body: some View {
if isEditing {
TextField("", text: $text)
.onSubmit {
isEditing.toggle()
// NOTE: reset document anytime a word ends in "?"
if text.last! == "?" {
print("resetting")
document.lines = [["Reset"]]
print(document.lines)
}
}
} else {
Text(text)
.onTapGesture {
isEditing.toggle()
}
}
}
}
class Document: ObservableObject {
@Published var lines: [[String]] = [["Hello"]]
}
我想要的是,我应该能够无限期地重置文本。但是,视图只会正确重置一次(请参见gif(。所有重置document.lines
的进一步更新都是不正确的,即使打印语句显示@Published
属性lines
正在明显更改。
我做错了什么?
您需要使用document.lines[index]更新文本字段文本,其中index是document.lines数组中行的索引。所以你需要更新如下。
struct CustomTextView: View {
@State var isEditing: Bool = false
@ObservedObject var document: Document
var body: some View {
if isEditing {
TextField("", text: $document.lines[index])
.onSubmit {
isEditing.toggle()
// NOTE: reset document anytime a word ends in "?"
if document.lines[index].last! == "?" {
print("resetting")
document.lines = [["Reset"]]
print(document.lines)
}
}
} else {
Text(text)
.onTapGesture {
isEditing.toggle()
}
}
}
}