UISearchBar 检测用户何时停止快速输入

问题描述 投票:0回答:6

我发现的大部分例子都在

Objective - C
中,这对我来说很难理解,有人可以在
Swift
中提供一个关于这个问题的例子吗? 这里是一种解决方案,但它在
Objective C
中。

ios swift uisearchbar
6个回答
14
投票
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()
}

8
投票

斯威夫特5

限制搜索

使用

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)
}

3
投票

你可以试试这个:

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.
    }
}

参考文献

链接 1,作者:swiftbysundell

github上的链接2


2
投票

您的链接的 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)
    }

1
投票

你必须使用 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)
}

0
投票
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.
}
© www.soinside.com 2019 - 2024. All rights reserved.