Updated 11 December 2023
Sometimes we need to use search suggestions within the same page that will show over the current screen for that we can use UISearchController with one Target Controller, for this follow these steps.
Here we are taking 2 controllers where one controller loads another controller over the screen.
Create A UIview On controller & create their outlet.
1 |
@IBOutlet weak var searchView: UIView! |
Now write this code on ViewDidLoad()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Upper Search page let vc = storyboard?.instantiateViewController(withIdentifier: "TableViewControllerClass") as! TableViewControllerClass searchController = UISearchController(searchResultsController: vc) searchController.hidesNavigationBarDuringPresentation = true searchController.searchBar.searchBarStyle = .default searchController.searchBar.backgroundImage = UIImage() searchController.searchBar.layer.borderWidth = 2; searchController.searchBar.layer.borderColor = UIColor.clear.cgColor //UIColor().HexToColor(hexString: ACCENT_COLOR).cgColor searchController.searchResultsUpdater = vc searchController.searchBar.delegate = vc searchController.searchBar.backgroundColor = UIColor().HexToColor(hexString: ACCENT_COLOR) searchController.searchBar.barTintColor = UIColor().HexToColor(hexString: ACCENT_COLOR) self.searchView.addSubview(searchController.searchBar) searchController.delegate = self self.definesPresentationContext = true |
Note: here “TableViewControllerClass” is another UITableViewController class that will load when the user clicks on the search bar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class TableViewControllerClass: UITableViewController ,UISearchResultsUpdating,UISearchBarDelegate { func updateSearchResults(for searchController: UISearchController) { self.searchtext = searchController.searchBar.text ?? "" // it will call when you type any Text } func searchBarCancelButtonClicked(_ searchBar: UISearchBar){ // tap on cancel click } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // Click on search button on keyboard } } |
Note: ” func updateSearchResults(for searchController: UISearchController)” this method will call every time when the user clicks on search bar & type on search bar so this method will help to reload the data or update the data in that controller.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.