qhh1ua
Last Updated: February 25, 2016
·
892
· girobai

How your first view controller can open the second view controller and set a text box

Picture

// ViewController.swift => view 1
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func generateRandomText()->String{
        var result:String?
        var random_num:Int = Int(arc4random_uniform(5))
        switch random_num {
        case 1:
            result = "hello1"
        case 2:
            result = "hello2"
        case 3:
            result = "hello3"
        case 4:
            result = "hello4"
        default:
            result = "hello0"
        }
        return result!
    }

    @IBAction func goToNextViewController(sender: AnyObject) {
        // storiboard ID of viewController2: "myViweC2"
        let viewController:ViewController2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("myViweC2") as ViewController2
        // .instantiatViewControllerWithIdentifier() returns AnyObject! this must be downcast to utilize it
        viewController.textFromParent = generateRandomText()
        self.presentViewController(viewController, animated: false, completion: nil)
    }

}
// ViewController2.swift => view 2
import UIKit

class ViewController2: UIViewController {

    var textFromParent:String!

    @IBOutlet weak var myLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myLabel.text = self.textFromParent
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

ref: http://stackoverflow.com/questions/11632043/use-of-delegates-to-communicate-between-view-controllers