27

I am trying to convert an app from Objective-C to Swift but I can't find how to pass data between views using Swift. My Objective-C code is

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController;
ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];

What that is doing is it basically takes the variable, theNum, and passes it to the variable, num, on a different view controller. I know this may be an easy question but I am getting pretty confused with Swift so if someone could explain how they changed it to Swift that would be greatly appreciated!

Thanks

zekel
  • 9,227
  • 10
  • 65
  • 96
lagoon
  • 6,417
  • 6
  • 23
  • 30
  • 2
    Its exactly the same in Swift, what exactly are you unsure about? – Jack Jun 14 '14 at 17:53
  • Just the Swift syntax in general. I know that I wouldn't be able to use the square brackets in Swift but in the eBook, it uses a . or parentheses at certain times and I'm not sure which one to use here – lagoon Jun 14 '14 at 17:55
  • The dot and parentheses syntaxes are very general programming syntaxes found in almost every language. To be **very** brief, `()` is used to call a function, `.` accesses members/properties/functions of a class/struct/etc. – Jack Jun 14 '14 at 17:58
  • Thanks, I have most of it figured out now except for the ansViewController.num = theNum part because it says UIViewController does not have a member named theNum – lagoon Jun 14 '14 at 18:07
  • [Here is a basic example](http://stackoverflow.com/a/31934101/3681880) – Suragch Aug 11 '15 at 05:57
  • 1
    @lagoon Would you mind accepting one of the answers? – gotnull Dec 09 '15 at 02:26

7 Answers7

37

Let's assumed we stand at the firstView go to the DetailView and want passing data from firstView to Detailview. To do that with storyboard, at the firstView we will have a method:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "segueTest") {
      //Checking identifier is crucial as there might be multiple
      // segues attached to same view
      var detailVC = segue!.destinationViewController as DetailViewController;
      detailVC.toPass = textField.text
    }
}

and then into the class of DetailView we declared a variable:

var toPass: String!

then you can use the variable toPass (of course you can change the type of the variable as you want, in this EX I just demo for string type).

Community
  • 1
  • 1
lee
  • 7,955
  • 8
  • 44
  • 60
  • best solution if you need something quick and easy! Thanks – Nicholas Aug 08 '15 at 10:42
  • 1
    This looks like what I am needing. I want to pass an array of variables from VC 1 to VC 2. Then, in VC 2, the user will enter information into more fields. That information will be appended to the array. When done, the array is sent to the cloud. I copied your code into my project and replaced my var names. I am getting an error, 'DispScreenOne does not have a member named 'toPass'. `{if (segue.identifier == "goToDispenseScreenTwo") { var DispScreenOne = segue.destinationViewController as! DispenseScreenTwoViewController; DispScreenOne.toPass = enteredDataArray.text }` – Greg Sep 01 '15 at 00:53
  • 1
    @Greg: Please make sure at **DispenseScreenTwoViewController**, you have a variable name **toPass** – lee Sep 01 '15 at 01:28
  • @Lee: I have a global var toPass. When I try to set a value to toPass in any of my view controllers, it recognizes the var. What am I missing? – Greg Sep 01 '15 at 22:17
  • You have a global variable toPass into your project doesn't mean **DispenseScreenTwoViewController** have this variable. So that you will get the error: **'DispScreenOne does not have a member named 'toPass'**. – lee Sep 02 '15 at 02:11
  • **DispScreenOne.toPass** mean that: at **DispenseScreenTwoViewController** you must have a variable name **toPass** – lee Sep 02 '15 at 02:14
  • it is not working unable to get value on second controller which is passed by first contrioller. – Chandni Apr 24 '18 at 09:09
19
class AnsViewController: UIViewController {
   var theNum: Int

    override func viewDidLoad() {
        super.viewDidLoad()

        println(theNum)
    }

}

override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let viewController = self.storyboard.instantiateViewControllerWithIdentifier("ansView") as AnsViewController
    viewController.num = theNum
    self.presentViewController(viewController, animated: true, completion: nil)
}
gotnull
  • 26,454
  • 22
  • 137
  • 203
2

To pass string or any data from one controller to another in swift.

Follows below steps:

1) Create property in child controller as var abc:string!

2) Create object of childcontroller

let storyboard:UIStoryboard()
let viewController: childcontroller = storyboard.instantiateViewControllerWithIdentifier("childcontroller") as! childcontroller
viewController.abc = "hello";
self.navigationController.pushviewController(Controller:viewController animated:true CompletionHandler:nil)
Miknash
  • 7,888
  • 3
  • 34
  • 46
Rizwan Shaikh
  • 273
  • 3
  • 8
0
Using tableview,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
        {
            let ClubProfileView = self.storyboard?.instantiateViewController(withIdentifier: "CBClubProfileViewController") as! CBClubProfileViewController

            let TempCulubDic:NSDictionary =
                ((ClubsListbyDateDic.object(forKey:((ClubsListbyDateDic.allKeys as! [String]).sorted(by: <)as NSArray).object(at: indexPath.section) as! String) as! NSArray).object(at: indexPath.row))as! NSDictionary

            let ClubId:String=(TempCulubDic.value(forKey: "club_id") as? String)!

            let CheckIndate:String=(TempCulubDic.value(forKey: "chekin_date") as? String)!

            ClubProfileView.ClubID=ClubId

            ClubProfileView.CheckInDate = CheckIndate

            // self.tabBarController?.tabBar.isHidden=true

            ClubProfileView.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ClubProfileView, animated: true)
            }
0
     @IBAction func nextbtnpreesd(_ sender: Any) {

            let mystring = "2"
            performSegue(withIdentifier: "MusicVC", sender: mystring)
        }



override func prepare(for segue: UIStoryboardSegue, sender: Any?) {


        if let destination = segue.destination as? MusicVC{

            if let song = sender as? String{
                destination.strlablevalie = song
            }
        }
    }

//in MusicVC create string like:

 var strlablevalie:String!
Paresh Hirpara
  • 487
  • 3
  • 10
  • it is not working unable to get value on second controller which is passed by first contrioller. – Chandni 2 mins ago edit – Chandni Apr 24 '18 at 09:13
0

To pass string or any data from one controller to another in swift.

Follows below steps:

1) Create variable of type which you want like (String,Int) var test : String!

2) Create object of childcontroller

 let vc = self.storyboard?.instantiateViewController(withIdentifier: "Here identifier of your VC") as! (Here Name Of Your Controller)
 vc.test = "Hello" (Or any data which you want to pass)
 self.navigationController?.pushViewController(VC, animated: true)

That should solve your problem

Sociopath
  • 13,068
  • 19
  • 47
  • 75
-1

Note: if we are using storyboard

Step 1: Master controller :

    // table row which row was selected
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        println("You selected cell #\(indexPath.row)!")

        nextScreenRow = indexPath.row

        // get to the next screen
        self.performSegueWithIdentifier("dashboard_static_screen_segue", sender: self)

    }

and then;

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        if (segue.identifier == "dashboard_static_screen_segue") {
            var detailController = segue.destinationViewController as StaticScreens;
            detailController.screenNumber = nextScreenRow
        }

    }// end prepareForSegue

step 2: Detail controller (StaticScreen)

// set variable into your detail controller

var screenNumber: NSInteger?

println("selected row \(screenNumber!)")
toing_toing
  • 2,334
  • 1
  • 37
  • 79
Vinod Joshi
  • 7,696
  • 1
  • 50
  • 51