一个SwiftUI onChange和task视图修饰符,带有额外的防抖时间。
import SwiftUI
import DebouncedOnChange
struct ExampleView: View {
@State private var text = ""
var body: some View {
TextField("Text", text: $text)
.onChange(of: text, debounceTime: .seconds(2)) { oldValue, newValue in
// Action executed each time 2 seconds pass since change of text property
}
.task(id: text, debounceTime: .milliseconds(250)) {
// Asynchronous action executed each time 250 milliseconds pass since change of text property
}
}
}
struct Sample: View {
@State private var debouncer = Debouncer() // 1. Store debouncer to control actions
@State private var query = ""
var body: some View {
TextField("Query", text: $query)
.onChange(of: query, debounceTime: .seconds(1), debouncer: $debouncer) { // 2. Pass debouncer to onChange
callApi()
}
.onKeyPress(.return) {
debouncer.cancel() // 3. Call cancel to prevent debounced action from running
callApi()
return .handled
}
}
private func callApi() {
print("Sending query \(query)")
}
}
将以下内容添加到你的 "Package.swift" 文件中的 dependencies 数组中
.package(url: "https://github.com/Tunous/DebouncedOnChange.git", .upToNextMajor(from: "1.1.0"))
或者将 https://github.com/Tunous/DebouncedOnChange.git 添加到 Xcode 中任何项目的 Swift 包列表中。