Last active
April 28, 2024 05:44
-
-
Save benigumocom/c10f2ad3e2bf871cac7e1c5b7e18193b to your computer and use it in GitHub Desktop.
【SwiftUI】TextField debounce | Debouncing TextField 👉 https://android.benigumo.com/20240427/textfield-debounce/
This file contains 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
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() | |
} |
Author
benigumocom
commented
Apr 28, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment