func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
print("after every text gets changed")
timer.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: #selector(ViewController.output), userInfo: searchText, repeats: false)
}
func output(){
print("hello")
if timer.userInfo != nil {
print(timer.userInfo)
}
timer.invalidate()
}
使用
NSObject.cancelPreviousPerformRequests
取消之前的触发器。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(ViewController.reload), object: nil)
self.perform(#selector(ViewController.reload), with: nil, afterDelay: 0.5)
}
@objc func reload() {
guard let searchText = searchBar.text else { return }
search(searchText)
}
你可以试试这个:
class WorkItem {
private var pendingRequestWorkItem: DispatchWorkItem?
func perform(after: TimeInterval, _ block: @escaping () -> Void) {
// Cancel the currently pending item
pendingRequestWorkItem?.cancel()
// Wrap our request in a work item
let requestWorkItem = DispatchWorkItem(block: block)
pendingRequestWorkItem = requestWorkItem
DispatchQueue.main.asyncAfter(deadline: .now() + after, execute: requestWorkItem)
}
}
//使用
lazy var workItem = WorkItem()
func searchBar(_ searchBar: UISearchBar, textDidChange: String) {
// 0.5 == half second
workItem.perform(after: 0.5) {
//Have Stopped, do something.
}
}
参考文献
您的链接的 Swift 版本:
var searchDelayer: Timer!
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchDelayer.invalidate(), searchDelayer = nil
if true {
searchDelayer = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.doDelayedSearch), userInfo: searchText, repeats: false)
}
}
func doDelayedSearch(_ t: Timer) {
assert(t == searchDelayer)
self.request(searchDelayer.userInfo!)
searchDelayer = nil
}
var priorSearchText = ""
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.request), object: priorSearchText)
priorSearchText = searchText
}
if true {
self.performSelector(#selector(self.request), withObject: searchText, afterDelay: 1.5)
}
你必须使用 UISearchBarDelegate 检查它:
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
//DO what you want
}
记得添加:
searchBar.delegate = self
以及他的相关协议:
UISearchBarDelegate
https://developer.apple.com/reference/uikit/uisearchbardelegate
该委托:
searchBarTextDidEndEditing
在键盘消失时被调用,因此将该代码添加到您的项目中:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
var timer: Timer?
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// Invalidate any existing timer to reset the delay each time text changes
timer?.invalidate()
// Initialize a new timer with a delay of 0.7 seconds
timer = Timer.scheduledTimer(withTimeInterval: 0.7, repeats: false) { [weak self] _ in
// Ensure we capture the latest text
guard let self = self, let text = searchBar.text else { return }
// Handle the search operation here, e.g., updating results based on 'text'
self.performSearch(with: text)
}
}
func performSearch(with query: String) {
print("Performing search with query: \(query)")
// Add actual search logic here, e.g., network request, data filtering, etc.
}