通过搜索栏创建一个segue到另一个视图控制器?

时间:2016-11-16 10:47:05

标签: swift uisearchbar

如何通过搜索栏创建到另一个视图控制器的segue? 结果的字符串值搜索栏以编程方式在newViewController中转换为新的String变量。我怎么能这样做?




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 个答案:

答案 0 :(得分:0)

首先,确保searchBar.delegate已连接到viewController。

您应该从searchBarSearchButtonClicked(_:)实施UISearchBarDelegate方法:

  

告诉代表点击了搜索按钮。

在您的情况下,当用户点击keyborad上的“搜索”按钮时,它将被调用。

所以,你应该做到以下几点:

// 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)
        }
    }
}

修改

如果您不使用storyboard(和segues),代码应该是:

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)
    }
}

希望这会有所帮助。