user5005376
user5005376

Reputation: 34

How to use multiple search bars on one viewController to access different JSON data in Swift?

I have a viewController with 3 different search bars on it and a button next to each search bar. The three search bars are for different categories(ie Movies, TV Shows) and when you press the button next to it its suppose to find an item at random based on what was entered in the search field. I know how to access the JSON data individually if there is only one search bar in the view Controller through appending the data to an array, but not if there are multiple search bars on the same view Controller. Sample Code for Search and JSON

Upvotes: 0

Views: 1727

Answers (2)

fingia
fingia

Reputation: 648

Short answer: Use the tag property (an integer) to identify each one.

Long answer:

You can do this via 1) the Interface Builder's View section. See pic. 2) programmatically yourSearchBar.tag =

Then, use the UISearchBarDelegate's func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) searchBar argument to determine which search bar triggered the delegate call.

It's true that you should follow the SOLID principles, though, whenever possible.

Tag under View section after clicking on a UISearchBar

Upvotes: 0

vikingosegundo
vikingosegundo

Reputation: 52227

by far the best option would be to have independent delegate objects for each search bar.

The second option would be to save each of the three searchbar on it's own property, ad distinguish in the delegate methods like

if searchBar == self.moviesSearchBar {
    //
} else if searchBar == self.tvshowSearchBar{
    //
}

Another option would be reconsidering the UI and have only one searchBar and a segmented control to switch the search scope.

Upvotes: 1

Related Questions