簡體   English   中英

在 SwiftUI 中更改在 TextEditor 上鍵入的字符

[英]Change characters typed on TextEditor in SwiftUI

我正在嘗試捕獲在 TextEditor 中鍵入的文本,將其存儲在變量中並更新 TextEditor 本身上顯示的內容。 我正在使用.onChange()來觸發和捕獲正在輸入的內容,將其存儲在變量中,並更改當前顯示的文本。 但問題是, .onChange()被調用了兩次:首先,當我在 TextEditor 中鍵入文本時; 其次,當我嘗試為視圖本身設置不同的字符時。

struct ChatView: View {
    @State var chatTextInput: String = ""
    @State var oldChatValue: String = ""
    @State var newChatValue: String = ""
    
    var body: some View {
        VStack {
            TextEditor(text: $chatTextInput)
                .onChange(of: chatTextInput) { newValue in
                    oldChatValue += "a"
                    newChatValue += newValue.last.map{String($0)}!
                    chatTextInput = oldChatValue
                    
                }
        }
    }
}

例如,如果我鍵入qwertynewChatValue將打印為Qawaearataya並且chatTextInput接收aaaaaaaaaaaaa

當我為 TextEditor 文本設置新字符時,有關如何防止 .onChange 被第二次觸發的任何線索?

非常感謝!

您的問題只是.onChange(of:)不是TextEditor的響應者,它是變量的響應者,在本例中chatTextInput 由於chatTextInput綁定到TextEditor ,當您鍵入一個字母時, chatTextInput會更新,並且.onChange(of:)運行。 但是,作為.onChange(of:)運行的一部分,您更改了再次調用chatTextInput .onChange(of:) again. You would have an infinite loop, except that .onChange(of:) again. You would have an infinite loop, except that .onChange(of:)` 在這一點上結束。 如果有人能解釋一下,我很想聽聽。

然而,解決方法是簡單地在.onChange(of:)中放置一個標志,以便每隔一次設置變量,如下所示:

struct ChatView: View {
    @State var chatTextInput: String = ""
    @State var oldChatValue: String = ""
    @State var newChatValue: String = ""
    
    @State var textEntryFlag = true
    
    var body: some View {
        VStack {
            TextEditor(text: $chatTextInput)
                .onChange(of: chatTextInput) { newValue in
                    if textEntryFlag {
                        oldChatValue += "a"
                        newChatValue += newValue.last.map{String($0)}!
                        chatTextInput = oldChatValue
                    }
                    textEntryFlag.toggle()
                }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM