Created
March 9, 2021 09:44
-
-
Save SergLam/ceff2bd060d37ee3d5cd7941743b7bd3 to your computer and use it in GitHub Desktop.
Debounce user input to text / search field - native Swift implementation
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 UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var mySrchBar: UISearchBar! | |
private var lastSearchTxt = "" | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
} | |
extension ViewController: UISearchBarDelegate { | |
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { | |
if lastSearchTxt.isEmpty { | |
lastSearchTxt = searchText | |
} | |
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.makeNetworkCall), object: lastSearchTxt) | |
lastSearchTxt = searchText | |
self.perform(#selector(self.makeNetworkCall), with: searchText, afterDelay: 0.7) | |
} | |
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { | |
searchBar.resignFirstResponder() | |
} | |
@objc private func makeNetworkCall(sender: String) { | |
print("\(sender)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment