3
votes

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() {

        }

1
This is kind of unclear, could you describe more about what are you trying to achieve?Ahmad F
User input to search Bar text. When user tap search button on keyboard Result of search bar need open new collection view with result. I need catch what user input, and pass this input to new value in new View Controller for further processingkukhtoa
It's better now, could you add some code in the question? I also suggest to add the description in comment as a part of the question to make it clearer.Ahmad F
@AhmadF, I added codekukhtoa
is it the answer for your question? :)Ahmad F

1 Answers

1
votes

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.