簡體   English   中英

觀察 SwiftUI TextField 上的變化

[英]Observe changes on SwiftUI TextField

我在玩 Swift UI。 我創建了一個包含所有我想要的元素的表格視圖(一個列表)。 按下鍵盤上的 Enter 鍵時,TextField 更改也在起作用。 很高興能如此快速地構建一個表格視圖;)。

但現在我想跟蹤文本字段上的每一個變化。 每次用戶輸入另一個文本時,我都想發送一個觸發搜索的請求。

這怎么能在我的代碼中完成? 我也在這里閱讀了這個文檔https://developer.apple.com/documentation/combine/receiving_and_handling_events_with_combine

我現在不知道如何在我的結構中使用它。

此處建議的解決方案TextField changes in SwiftUI不起作用(不再)

我會很感激你能與我分享的每一個提示和每一個想法。 我正在尋找解決方案的時間:(。

我的代碼如下所示:

import Foundation
import SwiftUI

struct MyListView: View {
    @ObservedObject var viewModel: MyViewModel

    @State private var query = ""

    var body: some View {

        NavigationView {
            List {
                // how to listen for changes here?
                // if I add onEditingChange here, Get the value only after the user finish search (by pressing enter on the keyboard)
                TextField(String.localizedString(forKey: "search_bar_hint"), text: self.$query) {
                    self.fetchListing()
                } 

                ForEach(viewModel.myArray, id: \.id) { arrayObject in
                    MyRow(arrayObj: arrayObject)
                }
            }
            .navigationBarTitle(navigationBarTitle())
        }
        .onAppear(perform: fetchListing)
    }

    private func fetchListing() {
        query.isEmpty ? viewModel.fetchRequest(for: nil) : viewModel.fetchRequest(for: query)
    }

    private func navigationBarTitle() -> String {
        return query.isEmpty ? String.localizedString(forKey: "my_title") : query
    }
}

一個簡單的自定義binding是此任務的良好開端:

struct ContentView: View {
    @State private var query = ""

    var body: some View {

        let binding = Binding<String>(
            get: { self.query },
            set: { self.query = $0; self.textFieldChanged($0) }
        )

        return NavigationView {
            List {
                TextField("Text", text: binding)
            }
        }
    }

    private func textFieldChanged(_ text: String) { print(text) }
}

它已經過測試和工作

開始了

struct ContentView: View {
    @State private var email = ""
    var body: some View {
        TextField("Email", text: $email)
            .onChange(of: email) { text in
                print(text)
            }
    }
}

暫無
暫無

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

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