Modifing one variable from another view controller swift

Deadly 提交于 2019-11-30 10:31:13
Tiago Lira

2 - "prepareForSegue" is called when you push a new view controller via the segue, but not when you dismiss it. No segue is called upon dismissal.

1 - A good way to do this would be the delegate pattern.

So the main view controller would be the delegate for the currencyViewController, and would receive a message when that controller is dismissed.

In the start of the currencyViewController file you prepare the delegate:

protocol CurrencyViewControllerDelegate {
  func currencyViewControllerDidSelect(value: String)
}

and you add a variable to the currencyViewController:

var delegate : CurrencyViewControllerDelegate?

Now, the mainViewController has to conform to that protocol and answer to that function:

class MainViewController : UIViewController, CurrencyViewControllerDelegate {
  //...  

  func currencyViewControllerDidSelect(value: String)  {
    //do your stuff here
  }
}

And everything is prepared. Last steps, in prepareForSegue (MainViewController), you will set the delegate of the currencyViewController:

var currencyVC = segue.destinationViewController as CurrencyViewController
currencyVC.delegate = self;

And when the user selects the value in currencyViewController, just call that function in the delegate:

self.delegate?.currencyViewControllerDidSelect("stuff")

A bit complex maybe, but it's a very useful pattern :) here is a nice tutorial with more info if you want it:

http://www.raywenderlich.com/75289/swift-tutorial-part-3-tuples-protocols-delegates-table-views

You have to use the parantheses to eval variables in strings, i.e. println("\(currencySelected)")

To access variables in the second view controller (the one which is the destination of the segue) you have to get a reference to it:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "presentCurrency") {
        let currencyViewController = segue.destinationViewController as CurrencyViewController // the name or your class here

        currencySelector.setTitle("\(currencyViewController.currencySelected)", forState: UIControlState.Normal)

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!