How can I debounce a method call?

前端 未结 13 1577
醉梦人生
醉梦人生 2020-11-30 01:18

I\'m trying to use a UISearchView to query google places. In doing so, on text change calls for my UISearchBar, I\'m making a request to google pla

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 01:39

    I used this good old Objective-C inspired method:

    override func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        // Debounce: wait until the user stops typing to send search requests      
        NSObject.cancelPreviousPerformRequests(withTarget: self) 
        perform(#selector(updateSearch(with:)), with: searchText, afterDelay: 0.5)
    }
    

    Note that the called method updateSearch must be marked @objc !

    @objc private func updateSearch(with text: String) {
        // Do stuff here   
    }
    

    The big advantage of this method is that I can pass parameters (here: the search string). With most of Debouncers presented here, that is not the case ...

提交回复
热议问题