Passing Data between View Controllers in Swift

2019-01-02 18:52发布

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

7条回答
栀子花@的思念
2楼-- · 2019-01-02 19:15

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!)")
查看更多
登录 后发表回答