2017-05-24 57 views
0

我試圖從一個VC(稱爲第二個VC)到另一個VC(第一個VC)傳遞一個文本值。第二個VC中的信息將決定第一個VC中文本字段的文本值。我曾嘗試使用文檔來解決這個問題,但我必須變得非常困惑或者其他的東西已經起來 - 我無法弄清楚。Swift 3.0使用Segue在視圖控制器之間傳遞信息

在我secondVC:

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

    if(segue.identifier == "saveSegue") { 

     let destinationVC = segue.destination as! firstVC 

     destinationVC.addressTextField.text = searchBar.text 
    } 
} 


@IBAction func savePressed(_ sender: Any) { 


    performSegue(withIdentifier: "saveSegue", sender: self) 
} 

segueing回firstVC後,文本框不與搜索欄的文字如預期填寫。 (searchBar文本不是零)根據我的理解,當在第二個VC中選擇按鈕並調用performSegue時,它還會調用prepareForSegue並設置addressTextField.text值,同時繼續回到第一個VC。我不確定我的邏輯是否正確。

+0

你使用的是navigationController嗎?你確定你實際上是在尋找'firstVC',而不是從naviationController棧中彈出'secondVC'嗎?在'prepareForSegue'中放置一個斷點,看它是否實際被調用。 – toddg

+0

我沒有使用導航控制器 - 只有情節串聯。我在prepareForSegue中設置了一個斷點,但它沒有被調用。這兩個有關係嗎? – Kevin

+2

通常,當你要回退到前一個viewController時,你實際上並沒有執行一個segue。您要麼關閉模式視圖segue,要麼從viewController堆棧中彈出視圖(如果您使用的是navigationController)。傳回數據有點複雜,我建議的做法是與代表一起進行。好信息[這裏](https://medium.com/ios-os-x-development/pass-data-with-delegation-in-swift-86f6bc5d0894) – toddg

回答

1

在你FirstViewController

@IBAction func dismissSearchVC(_ sender: UIStoryboardSegue) { 
     let sourceVC = sender.source as! viewController2 
     addressTextField.text = sourceVC.searchBar.text 
} 

在你secondViewController

var searchedText = "" 


@IBAction func savePressed(_ sender: Any) { 
    performSegue(withIdentifier: "saveSegue", sender: self) 
} 

現在連接您的viewController從下拉

退出在上面,添加一個標識符,該賽格瑞作爲saveSegue並選擇dismissSearchVC

enter image description here

enter image description here

然後從這裏選擇賽格瑞 enter image description here

現在選擇「放鬆順着接下去DismissSearchVC」,並在屬性檢查器中添加標識..

+1

我的prepareForSegue甚至沒有調用,所以這是行不通的 – Kevin

+2

其實你正在做一個流行或解僱viewController所以它不叫... 等待我編輯我的答案 –

+0

addressTextField是在firstViewController,所以在secondViewController viewDidLoad,addressTextField.text = searchingText產生一個錯誤 – Kevin

0

我懷疑從一個視圖控制器到另一個你的過渡視圖控制器沒有發生,因爲segue,而是因爲按鈕的連接而發生。

刪除您從UIButton連接到AnotherViewController所連接的segue

現在從包含ViewController的按鈕中添加segueAnotherViewController。 (不是從UIButtonAnotherViewController,而是從ViewControllerAnotherViewController)。並給你segue你的預期標識符。

相關問題