2016-11-16 72 views
0

如何通過搜索欄創建一個segue到另一個視圖控制器? 結果的字符串值以編程方式在NewViewController中搜索欄切換到新的字符串變量。我如何做到這一點?通過搜索欄創建一個segue到另一個視圖控制器?

 



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

     } 

+0

這有點不清楚,你能描述更多關於什麼是你想達到什麼目的? –

+0

用戶輸入來搜索欄文字。當用戶點擊鍵盤上的搜索按鈕搜索欄的結果需要打開新的收集視圖結果。我需要趕上什麼用戶輸入,並在新的視圖控制器通過這個輸入新值作進一步處理 –

+0

這是現在好了,你可以在問題中添加一些代碼?我還建議將評論中的描述作爲問題的一部分加以說明,以使其更清楚。 –

回答

0

首先,確保searchBar.delegate連接到ViewController。

您應該UISearchBarDelegate實施searchBarSearchButtonClicked(_:)方法:

Tells the delegate that the search button was tapped.

在你的情況下,將得到當用戶點擊了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) 
     } 
    } 
} 

編輯:

如果你不使用故事板(和塞格斯),代碼應該是這樣的:

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

希望這有助於。

+0

我有這個錯誤:沒有segue與標識符'searchView –

+0

爲什麼?你必須在故事板兩個viewControllers之間創建...如果你不知道如何做到這一點,選中[這個答案](http://stackoverflow.com/questions/39904328/xcode-where-to-分配最SEGUE標識符/ 39905378#39905378) –

+0

我沒有用故事板在這個項目 –

相關問題