Forked from carlynorama/debouncingTextField.swift
Created
September 17, 2022 16:53
-
-
Save byaruhaf/ac8bcb9cd40631db2baa6132ace3e2fc to your computer and use it in GitHub Desktop.
Debouncing Text Field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// DebouncingTextField.swift | |
// LocationSearchResults | |
// | |
// Created by Labtanza on 8/13/22. | |
// https://stackoverflow.com/questions/66164898/swiftui-combine-debounce-textfield | |
// https://stackoverflow.com/questions/62635914/initialize-stateobject-with-a-parameter-in-swiftui | |
import SwiftUI | |
class TextFieldObserver : ObservableObject { | |
@Published var debouncedText = "" | |
@Published var searchText = "" | |
init(delay: DispatchQueue.SchedulerTimeType.Stride) { | |
$searchText | |
.debounce(for: delay, scheduler: DispatchQueue.main) | |
.assign(to: &$debouncedText) | |
} | |
} | |
struct DebouncingTextField : View { | |
var promptText:String = "" | |
@Binding var debouncedText : String | |
@StateObject private var textObserver:TextFieldObserver | |
init(_ prompt:String, text binding:Binding<String>, debounceDelay:Double) { | |
self.promptText = prompt | |
self._debouncedText = binding | |
//only okay because this stateobject is NOT a persistant ViewModel, | |
//it only matters for this and only this instance. | |
self._textObserver = StateObject(wrappedValue: TextFieldObserver(delay: DispatchQueue.SchedulerTimeType.Stride(floatLiteral: debounceDelay))) | |
} | |
var body: some View { | |
TextField(promptText, text: $textObserver.searchText) | |
.onReceive(textObserver.$debouncedText) { (val) in | |
debouncedText = val | |
} | |
} | |
} | |
struct WidgetBoard: View { | |
@State var debouncedTextField:String = "" | |
var body: some View { | |
VStack { | |
DebouncingTextField("Enter text", text: $debouncedTextField, debounceDelay: 2.0).border(.gray) | |
Text(debouncedTextField) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment