Josip Bogdan
Josip Bogdan

Reputation: 588

SWIFT: When i create a secondViewController, how to access to variables from original ViewController

When I go to my secondViewController using

let secondViewController:SecondViewController = SecondViewController()

self.presentViewController(secondViewController, animated: true, completion: nil)

I know I can send varibles to SECOND ONE using secondViewController.theNum = num, but while secondViewController is presented how to send varibles bar to the original ViewController.

Thing is I would like to start viewdidload() on original ViewController after this part of code is finished

self.dismissViewControllerAnimated(true, completion:nil)

Upvotes: 1

Views: 102

Answers (1)

Steve Rosenberg
Steve Rosenberg

Reputation: 19524

Here are the full classes for two Views from a project where I pass data to a detail view and use a protocol/delegate method to return data to the first view:

View 1:

import UIKit

class Contacts: UITableViewController, dataUpdated {


    //Declaring contact structure
    struct contactInfo {
        var name: String
        var phoneNumber: String
    }

    var listOfContacts: [contactInfo] = []
    var Duration = 100

    //Sample contacts
    var firstContact = contactInfo(name: "John Coffey" , phoneNumber: "(111) 111-1111")
    var secondContact = contactInfo(name: "Cathy Kane" , phoneNumber: "(222) 222-2222")



    //TableView delegates
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return listOfContacts.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("contact", forIndexPath: indexPath) as UITableViewCell


        cell.textLabel?.text = listOfContacts[indexPath.row].name
        cell.detailTextLabel?.text = listOfContacts[indexPath.row].phoneNumber


        return cell
    }

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        if editingStyle == .Delete {
            listOfContacts.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
    }

    //ViewController lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.leftBarButtonItem = self.editButtonItem()

        listOfContacts.append(firstContact)
        listOfContacts.append(secondContact)
    }

    //Passing details to detail VC
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "ToDetail" {

            let indexPath = self.tableView.indexPathForSelectedRow()
            let theSelectedRow = listOfContacts[indexPath!.row]
            let theDestination = (segue.destinationViewController as ContactDetails)

            theDestination.contactName = theSelectedRow.name
            theDestination.contactPhone = theSelectedRow.phoneNumber
        } else if segue.identifier == "ToInput" {

            (segue.destinationViewController as ContactInput).delegate = self
        }
    }


    override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

        let fromContact = listOfContacts[sourceIndexPath.row]
        listOfContacts.removeAtIndex(sourceIndexPath.row)
        listOfContacts.insert(fromContact, atIndex: destinationIndexPath.row)
    }

    //Delegate method to update the array with new contact
    func didUpdateContact(senderClass: AnyObject, aName: String, aPhoneNumber: String) {

        var newContact = contactInfo(name: aName, phoneNumber: aPhoneNumber)
        listOfContacts.append(newContact)
        println(listOfContacts)

        self.tableView.reloadData()
    }

}

View2:

import UIKit

protocol dataUpdated:NSObjectProtocol {

    func didUpdateContact(senderClass: AnyObject, aName: String, aPhoneNumber: String)

}

class ContactInput: UIViewController, UITextFieldDelegate {

    //Properties
    var name = ""
    var phoneNumber = ""
    var delegate: dataUpdated?

    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var phoneField: UITextField!



    //Textfield delegates
    func textFieldShouldReturn(textField: UITextField!) -> Bool {

        if textField.tag == 1 {

            self.name = textField.text
        }

        else {

            self.phoneNumber = textField.text
        }

        textField.resignFirstResponder()
        return true
    }

    //Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        self.nameField.delegate = self
        self.phoneField.delegate = self
    }


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


    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        if name != "" && phoneNumber != "" {
            self.delegate!.didUpdateContact(self, aName: self.name, aPhoneNumber: self.phoneNumber)
        }
    }
}

Upvotes: 1

Related Questions