首页 文章

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

提问于
浏览
0

如何通过搜索栏创建一个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

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

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

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

    在您的情况下,当用户点击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)
            }
        }
    }
    

    EDIT:

    如果您不使用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)
        }
    }
    

    希望这有帮助 .

相关问题