Alexei Kukhto Alexei Kukhto - 22 days ago 10
Swift Question

Create a segue to another view controller through search bar?

How to create a segue to another view controller through search bar?
String value of result Search Bar segue to new String variable in newViewController programmatically. How I can do it?





func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// Here I'm trying catch user input

userInput = "http://api.giphy.com/v1/gifs/search?" + "q=" + searchBar.text! + "&api_key=dc6zaTOxFJmzC"
performSegue(withIdentifier: "searchView", sender: self)

}




//My segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue .identifier == "searchView" {
let DestViewController = segue.destination as! SearchResultController
DestViewController.userInputRequest = userInput
}





//My new View Controller
class SearchResultController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {

var userInputRequest: String = ""
let userRequestArray = [Image]()
override func viewDidLoad() {

}


Answer

First, make sure that searchBar.delegate is connected to the viewController.

You should implement searchBarSearchButtonClicked(_:) method from UISearchBarDelegate:

Tells the delegate that the search button was tapped.

In your case, it will be get called when the user taps the "Search" button on the keyborad.

So, you should the following:

// don't forget to add 'UISearchBarDelegate'
class ViewController: UIViewController, UISearchBarDelegate {

   //...

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let text = searchBar.text {
            // here is text from the search bar
            print(text)

            userInput = text

            // now you can call 'performSegue'
            performSegue(withIdentifier: "searchView", sender: self)
        }
    }
}

EDIT:

If you are not using storyboard (and segues), code should be like:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    if let text = searchBar.text {
        // here is text from the search bar
        print(text)

        let searchResultController: SearchResultController = SearchResultController()
        searchResultController.userInputRequest = text
        navigationController?.pushViewController(searchResultController, animated: true)
    }
}

Hope this helped.