Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active April 28, 2024 05:44
Show Gist options
  • Save benigumocom/c10f2ad3e2bf871cac7e1c5b7e18193b to your computer and use it in GitHub Desktop.
Save benigumocom/c10f2ad3e2bf871cac7e1c5b7e18193b to your computer and use it in GitHub Desktop.
【SwiftUI】TextField debounce | Debouncing TextField 👉 https://android.benigumo.com/20240427/textfield-debounce/
import SwiftUI
import Throttler
struct TestDebounceTextField: View {
@State var debouncedText = ""
var body: some View {
VStack {
Text("\(debouncedText)")
Text("\(debouncedText.count)")
TextField("Normal", text: $debouncedText)
DebounceTextField3(titleKey: "Search-3", debouncedText: $debouncedText)
DebounceTextField4(titleKey: "Search-4", debouncedText: $debouncedText)
}
.font(.largeTitle)
.textFieldStyle(.roundedBorder)
.padding()
}
}
struct DebounceTextField3: View {
var titleKey: String
@Binding var debouncedText: String
@State private var delay: Task<Void, Never>?
var body: some View {
TextField(
titleKey,
text: Binding(
get: { debouncedText },
set: { newvalue in
delay?.cancel()
delay = Task {
do {
try await Task.sleep(for: .seconds(0.25))
} catch { return }
debouncedText = newvalue
}
}
)
)
}
}
struct DebounceTextField4: View {
var titleKey: String
@Binding var debouncedText: String
var body: some View {
TextField(
titleKey,
text: Binding(
get: { debouncedText },
set: { newvalue in
debounce(.seconds(0.25)) {
debouncedText = newvalue
}
}
)
)
}
}
#Preview("CustomBinding") {
TestDebounceTextField()
}
@benigumocom
Copy link
Author

sc 2024-04-28 at 14 22 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment