Vin*_*uan 6 text-editor swiftui
我正在构建一个笔记应用程序,并且有一个笔记编辑视图,其中使用一些文本编辑器来监听用户的输入。现在,一个环境对象被传递到此注释编辑视图,我设计了一个保存按钮来保存更改。它运行良好,只是用户必须单击“保存”按钮才能更新模型。
编辑完成后,文本编辑器应更新环境对象实例的值。不一定要单击“保存”按钮来保存更改。
struct NoteDetails: View {
@EnvironmentObject var UserData: Notes
@Binding var selectedNote: SingleNote?
@Binding var selectedFolder: String?
@Binding var noteEditingMode: Bool
@State var title:String = ""
@State var updatedDate:Date = Date()
@State var content: String = ""
var id: Int?
var label: String?
@State private var wordCount: Int = 0
var body: some View {
VStack(alignment: .leading) {
TextEditor(text: $title)
.font(.title2)
.padding(.top)
.padding(.horizontal)
.frame(width: UIScreen.main.bounds.width, height: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
Text(updatedDate, style: .date)
.font(.subheadline)
.padding(.horizontal)
Divider()
TextEditor(text: $content)
.font(.body)
.lineSpacing(15)
.padding(.horizontal)
.frame(maxHeight:.infinity)
Spacer()
}
}
}
Run Code Online (Sandbox Code Playgroud)
UserData.editPost(label: label!, id: id!, data: SingleNote(updateDate: Date(), title: title, body: content))
Run Code Online (Sandbox Code Playgroud)
@Published var NoteList: [String: [SingleNote]]
,我尝试将 $UserData.NoteList[label][id].title 传递到 TextEditor,但它也不被接受在网上没有找到完善的解决方案,所以在这里提出这个问题。提前感谢您的建议!
Mof*_*waw 12
我不知道编辑完成后保存的确切含义。这是我发现的两种可能的方法。
注意:在以下演示中,蓝色背景的文本显示已保存的文本。
解决方案:添加点击手势,让用户在TextEditor
. save()
同时打电话。
代码:
struct ContentView: View {
@State private var text: String = ""
@State private var savedText: String = ""
var body: some View {
VStack(spacing: 20) {
Text(savedText)
.frame(width: 300, height: 200, alignment: .topLeading)
.background(Color.blue)
TextEditor(text: $text)
.frame(width: 300, height: 200)
.border(Color.black, width: 1)
.onTapGesture {}
}
.onTapGesture { hideKeyboardAndSave() }
}
private func hideKeyboardAndSave() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
save()
}
private func save() {
savedText = text
}
}
Run Code Online (Sandbox Code Playgroud)
解决方案:使用Combine
with仅在几秒钟后没有进一步事件发生.debounce
后才发布和观察。x
我设置x
为3。
代码:
struct ContentView: View {
@State private var text: String = ""
@State private var savedText: String = ""
let detector = PassthroughSubject<Void, Never>()
let publisher: AnyPublisher<Void, Never>
init() {
publisher = detector
.debounce(for: .seconds(3), scheduler: DispatchQueue.main)
.eraseToAnyPublisher()
}
var body: some View {
VStack(spacing: 20) {
Text(savedText)
.frame(width: 300, height: 200, alignment: .topLeading)
.background(Color.blue)
TextEditor(text: $text)
.frame(width: 300, height: 200)
.border(Color.black, width: 1)
.onChange(of: text) { _ in detector.send() }
.onReceive(publisher) { save() }
}
}
private func save() {
savedText = text
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5978 次 |
最近记录: |